一个选择语句,在同一列上具有多个Group BY

时间:2019-01-26 19:07:01

标签: sql sql-server select group-by

我有这样的“ TABLE_A”:

TVA  Amount   InvoiceID
----------------------
22  | 10.00 | inv-12
22  |-14.00 | inv-13
25  | 24.00 | inv-14
25  |-36.00 | inv-15
25  |-25.00 | inv-16
25  | 18.50 | inv-17
24  |-16.50 | inv-18
24  | 10.00 | inv-19

目标是通过TABLE_A.TVA值并使SUM(TABLE_A.Amount)> 0和SUM(TABLE_A.Amount)<0成为groupB,最终得到按TVA值分组的所有正数之和,所有负金额的总和也按其TVA值分组

我的查询是这样的:

SELECT TABLE_A.TVA, TABLE_A.InvoiceID,
       SUM(TABLE_A.Amount) AS [PositiveTotalAMount],
       SUM(TABLE_A.Amount) AS [NegativeTotalAMount]  

 FROM TABLE_A
 GROUP BY TABLE_A.TVA
 HAVING SUM(TABLE_A.TVA) > 0

我的问题是如何在负值上添加第二个分组,因为这里我仅在SUM()> 0上分组

2 个答案:

答案 0 :(得分:1)

您可以使用CASE (Transact-SQL)表达式:

SELECT
    A.TVA,
    A.InvoiceID,
    SUM(CASE WHEN A.Amount > 0 THEN A.Amount ELSE 0 END) AS [PositiveTotalAMount],
    SUM(CASE WHEN A.Amount < 0 THEN A.Amount ELSE 0 END) AS [NegativeTotalAMount]
FROM
    TABLE_A A
GROUP BY
    A.TVA,
    A.InvoiceID

此外,您还必须包括选择列表中未聚合到GROUP BY列表的所有列。 InvoiceID丢失。

我还为A使用别名TABLE_A来提高可读性。

答案 1 :(得分:0)

有条件聚合:

SELECT 
  TABLE_A.TVA, 
  SUM(CASE WHEN TABLE_A.Amount > 0 THEN TABLE_A.Amount ELSE 0 END) AS [PositiveTotalAMount],
  SUM(CASE WHEN TABLE_A.Amount < 0 THEN TABLE_A.Amount ELSE 0 END) AS [NegativeTotalAMount]  
 FROM TABLE_A
 GROUP BY TABLE_A.TVA

如果要在分组中包括列TABLE_A.InvoiceID,则:

SELECT 
  TABLE_A.TVA, 
  TABLE_A.InvoiceID, 
  SUM(CASE WHEN TABLE_A.Amount > 0 THEN TABLE_A.Amount ELSE 0 END) AS [PositiveTotalAMount],
  SUM(CASE WHEN TABLE_A.Amount < 0 THEN TABLE_A.Amount ELSE 0 END) AS [NegativeTotalAMount]  
 FROM TABLE_A
 GROUP BY TABLE_A.TVA, TABLE_A.InvoiceID