2017-08-07 75 views
1

我想基於數量值來計算數量的總和如何在使用SQL Server的情況下進行分組?

對於實例

ItemNo Quantity 
------------------ 
111  5 
111  -2 
111  3 
112  10 

我想ItemNo做分組和計算像下面

ItemNo Quantity Positive Negative 
----------------------------------------- 
111  6   8   -2 
112  10   10   0 

我想這樣的

SELECT 
    ItemNo, 
    Sum(Quantity), 
    Case when Quantity >= 0 then sum(quantity) else 0 end POSITIVE, 
    Case when Quantity < 0 then sum(quantity) else 0 end Negative 
From 
    Sales 
Group By 
    ItemNo, 
    Quantity 

我知道這個分組是錯誤的。我的查詢應該如何?

感謝

+0

可能的重複[在SQL Server中使用CAS函數和SUM函數](https://stackoverflow.com/questions/17612387/use-case-statement-with-sum-function-in-sql-服務器) –

回答

6

只要把SUM()在你的CASE()語句:

SELECT 
    ItemNo, 
    Sum(Quantity), 
    SUM(Case when Quantity >= 0 then quantity else 0 end) POSITIVE, 
    SUM(Case when Quantity < 0 then quantity else 0 end) Negative 
From 
    Sales 
Group By 
    ItemNo; 

此外,刪除Quantity從GROUP BY。您正在使用sum()彙總quantity,所以對GROUP BY它也是無稽之談。

+0

愚蠢的錯誤。謝謝你兄弟 –

0

如果我有信譽,我會把這留作JNevill的回答的一個評論,但你也想給數量和一個別名來得到問題的結果。例如:SELECT ItemNo, Sum(Quantity) Quantity, SUM(Case when Quantity >= 0 then Quantity else 0 end) Positive, SUM(Case when Quantity < 0 then Quantity else 0 end) Negative From Sales Group By ItemNo;

相關問題