基于另一个表的MySQL SELECT SUM(另一个案例)

时间:2018-03-12 09:47:57

标签: php mysql sql

继续我之前的question。但现在我在下面添加一些条件:

根据工作查询代码:

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 = 'DP0002'
GROUP BY R.budgetid_fk;

在该代码上,它将获得某些列的总价格。

requestid      | budgetid_fk    | category  | itemid_fk | quantity | currencyid_fk | price | discount | userid_fk
RQ201803000001 | BU201803000002 | Item      | IT0001    |          |       |
RQ201803000002 | BU201803000002 | Project   |           | 20       | CU0002 | 750 | 10 | US0004

现在我需要添加额外的代码来计算类别项目( RQ201803000002

价格累计

SUM(R.quantity * I.price * COALESCE(CC.amount,1)) as total

逻辑:

(quantity * (price * currency)) - discount as total2

*need to convert the currency first
*get department from userid_fk

然后累积它

total + total2

你可以看到sql fiddle here

1 个答案:

答案 0 :(得分:0)

我想你只是想要这个(如果Arrow来自另一个表,那么除外)。

discount