简体   繁体   English

在我的情况下,如何使用SQL Server进行分组?

[英]How can I do grouping in my case using SQL Server?

I wants to calculate sum of quantity based on Quantity value 我想根据数量值计算数量之和

For Example 例如

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

I want to do grouping by ItemNo and calculate like below 我想按ItemNo进行分组并按如下方式进行计算

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

I tried like this 我尝试过这样

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

I know this grouping is wrong. 我知道这种分组是错误的。 How my query should be? 我的查询应该如何?

thanks 谢谢

Just put the SUM() around your CASE() statement: 只需将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;

Also, remove Quantity from your GROUP BY. 另外,从GROUP BY中删除“ Quantity You are aggregating quantity with a sum() so it's nonsense to GROUP BY it as well. 您正在将quantity与sum()进行聚合,因此对GROUP BY也很无聊。

I would leave this as a comment to JNevill's answer if I had the reputation, but you would also want to give the quantity sum an alias to get the results in the question. 如果我有声誉,我将其作为对JNevill答案的注释,但您也想给数量和起一个别名,以获取问题中的结果。 For example: 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; 例如: 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM