Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

MySQL SELECT SUM baseado em outra tabela


Acho que estraguei um pouco o seu FK, mas pelo menos você tem o espírito;)

SQL Fiddle

Configuração do esquema MySQL 5.6 :

Consulta 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

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