这是我的SQL查询的某个部分:
SELECT pir.paymentInstrumentItemID AS id,
SUM(pir.priceChange) AS priceSum,
pir.clientInfoID AS clientID,
IFNULL(SUM(pir.costChange), 0) AS selfPrice,
pir.paymentInstrumentItemID
FROM paymentInstrumentRegister as pir
GROUP BY pir.paymentInstrumentItemID
我需要做的是计算在第一个SUM函数内部分组的行数,并从中生成一个CASE语句,如下所示:
SUM(CASE WHEN amtRows = 1 THEN 0 ELSE pir.priceChange) as priceSum
所以基本上只要有一行我就不需要这个值,但只要有两个或更多,我需要他们的总和。
非常感谢您的反馈。
答案 0 :(得分:1)
我认为最好的选择是将COUNT()
添加到查询中,让编程语言完成其余的工作,但如果您真的需要通过MySQL执行此操作:
SELECT
id,
(CASE WHEN amtRows = 1 THEN 0 ELSE priceSum) as priceSum,
amtRows,
clientID,
selfPrice,
paymentInstrumentItemID
FROM (
SELECT
pir.paymentInstrumentItemID AS id,
SUM(pir.priceChange) AS priceSum,
COUNT(pir.priceChange) as as amtRows,
pir.clientInfoID AS clientID,
IFNULL(SUM(pir.costChange),0) AS selfPrice,
pir.paymentInstrumentItemID
FROM
paymentInstrumentRegister as pir
GROUP BY
pir.paymentInstrumentItemID
) tmp