如何使用SQL Server对我的案例进行分组?

Lia*_*san 1 sql sql-server stored-procedures

我想根据数量值计算数量之和

例如

ItemNo    Quantity
------------------
111       5
111       -2
111       3
112       10
Run Code Online (Sandbox Code Playgroud)

我想做分组ItemNo并计算如下

ItemNo    Quantity    Positive   Negative
-----------------------------------------
111       6            8           -2
112       10           10          0
Run Code Online (Sandbox Code Playgroud)

我试过这样的

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
Run Code Online (Sandbox Code Playgroud)

我知道这种分组是错误的.我的查询应该如何?

谢谢

JNe*_*ill 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;
Run Code Online (Sandbox Code Playgroud)

另外,Quantity从GROUP BY中删除.您正在quantity使用sum()进行聚合,因此对GROUP BY也是无意义的.