我尝试在SUM()函数中使用嵌套的CASE WHEN语法,但是自3天以来什么都没作用
当我检索所有求和和嵌套条件时,代码会很好工作
我解释:
所以我想做的是让每个客户在实际月份中损失所有财务损失,并将所有这些金额相加
SELECT
SUM(pertes) AS pertes_reelles
FROM
(SELECT
c.ID_clt,
SUM(CASE
WHEN
((co.Qac_cont - SUM(CASE
WHEN Quantite_cmd IS NULL THEN 0
ELSE Quantite_cmd
END)) * - 1) < 0
THEN
((co.Qac_cont - SUM(CASE
WHEN Quantite_cmd IS NULL THEN 0
ELSE Quantite_cmd
END)) * - 1)
ELSE 0
END) * co.Prix_TTC AS pertes
FROM
clients c
LEFT JOIN contrat co ON co.clt_ID = c.ID_clt
LEFT JOIN commande cmd ON cmd.clt_ID = c.ID_clt
AND MONTH(DATE(cmd.date_livr_cmd)) = MONTH(DATE('2019-08-30 09:23:23'))
WHERE
c.Etat_clt <> 'D'
GROUP BY c.ID_clt) AS liste
答案 0 :(得分:0)
就像@BobJarvis说的那样,问题出在嵌套的SUM上,所以我分解了嵌套的处理过程,谢谢!新的请求:
SELECT SUM(CASE
WHEN
perte < 0
THEN
perte * - 1
ELSE 0
END) AS pertes_reelles
FROM
(SELECT
c.ID_clt, co.Prix_TTC, ((co.Qac_cont - SUM(CASE
WHEN Quantite_cmd IS NULL THEN 0
ELSE Quantite_cmd
END)) * - 1) as ecart, co.Prix_TTC * ((co.Qac_cont - SUM(CASE
WHEN Quantite_cmd IS NULL THEN 0
ELSE Quantite_cmd
END)) * - 1) as perte
FROM
clients c
LEFT JOIN contrat co ON co.clt_ID = c.ID_clt
LEFT JOIN commande cmd ON cmd.clt_ID = c.ID_clt
AND MONTH(DATE(cmd.date_livr_cmd)) = MONTH(DATE('".$today."'))
WHERE
c.Etat_clt <> 'D'
GROUP BY c.ID_clt) AS liste