适当的聚合功能,或如何绕过它

时间:2012-10-12 00:10:07

标签: sql sql-server-2008

我正在尝试使用“CASE”操作来执行select语句,但它说我的条件(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

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

FROM TransactionsDB

GROUP BY ID

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

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

提前谢谢!!!!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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