Mysql
 sql >> Base de données >  >> RDS >> Mysql

MySQL SELECT SUM basé sur une autre table

Je pense que je me suis un peu trompé dans ton FK, mais au moins tu as l'esprit;)

SQL Fiddle

Configuration du schéma MySQL 5.6 :

Requête 1 :

SELECT
    R.budgetid_fk,
    SUM(R.quantity),
    SUM(R.quantity * I.price * COALESCE(CC.amount,1)) as total, 
    B.budgetid,
    B.budget_month
FROM tb_pro_request R 
INNER JOIN tb_items I 
  ON R.itemid_fk = I.itemid
INNER JOIN tb_budgets B 
  ON R.budgetid_fk = B.budgetid 
  AND B.active = 'Y'
LEFT JOIN tb_currency_converters CC 
  ON CC.from_currencyid_fk = I.currencyid_fk 
  AND CC.to_currencyid_fk = B.currencyid_fk
WHERE
    R.investmentid_fk = '' 
    AND (
      R.approval_status = 'P' 
      OR R.approval_status = 'A'
    ) 
    AND DATE_FORMAT(B.budget_month,'%Y-%m') = '2018-03' 
    AND B.departmentid_fk = 'DP0003'
GROUP BY R.budgetid_fk

Résultats :

|    budgetid_fk | SUM(R.quantity) |             total |       budgetid | budget_month |
|----------------|-----------------|-------------------|----------------|--------------|
| BU201803000001 |               7 | 575.2840143424692 | BU201803000001 |   2018-03-01 |