[英]How to count the amount of rows being summed inside an SQL SUM function?
Here's a certain part of my SQL query: 这是我的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
What I need to do is to count the amount of rows that got grouped by inside the first SUM function and make a CASE statement out of it, so something like that: 我需要做的是计算在第一个SUM函数中按行分组的行数,并用它做一个CASE语句,所以像这样:
SUM(CASE WHEN amtRows = 1 THEN 0 ELSE pir.priceChange) as priceSum
So basically whenever there is a single row I don't need the value, but as long as there's two or more of those, I need their sum. 因此,基本上只要有一行,我就不需要该值,但是只要有两个或多个,我就需要它们的总和。
Will appreciate feedback. 将不胜感激反馈。
I think the best option is to add COUNT()
to query, and let programming language to do the rest, but if you really need do that by MySQL: 我认为最好的选择是添加
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.