1

我正在尝试使用“CASE”操作执行选择语句,但它说我的条件 (abc.reason) 无效,因为它既不包含在聚合函数也不包含在 GROUP BY 子句中。我尝试将它添加到 GROUP BY 子句,但在我的结果表中创建了一个不必要的行。有小费吗?

SELECT

DISTINCT ID 
,(CASE WHEN reason = 4 THEN null ELSE SUM(quantity*price) END) AS Value
,COUNT(*) AS CountAll

FROM TransactionsDB

GROUP BY ID

ORDER BY ID DESC

如果我将 GROUP BY 子句更改为,GROUP BY ID, reason那么我的结果是:

ID ---- VALUE ----- COUNTALL

id1 - - 1000 - - - - - 22

id1 - - - NULL - - - - 1

id2 - - - - 232 - - - 17

id3 - - - - 113 -- - - 2

id3 - - - - NULL - - 1

当我真的需要结果时:

ID ---- VALUE ----- COUNTALL

id1 - - 1000 - - - - - 23

id2 - - - - 232 - - - 17

id3 - - - - 113 -- - - 3

先感谢您!!!!

4

2 回答 2

0
SELECT ID 
,SUM(CASE WHEN reason = 4 THEN 0 ELSE quantity*price END) AS Value
,COUNT(*) AS CountAll
FROM TransactionsDB
GROUP BY ID
ORDER BY ID DESC
于 2012-10-12T00:14:42.417 回答
0
SELECT DISTINCT ID,
    SUM(CASE WHEN reason = 4 THEN 0 ELSE quantity*price END) AS Value,
    COUNT(*) AS CountAll
FROM TransactionsDB
GROUP BY ID
ORDER BY ID DESC
于 2012-10-12T00:15:09.163 回答