SQL Server:按两列分组,并将第三列与两个分组

时间:2017-04-24 09:23:03

标签: sql sql-server sql-server-2005

我正在创建一个发票系统,我需要使用两个过滤器来获取total_amount的总和,即monthcategory_of_service

到目前为止,我可以根据两个过滤器使用GROUP BY子句,但我的SUM计算为整体,而不是根据组。

我提到了各种问题但却无法找到我的解决方案。

MySQL: Group by two columns and sum

month | category_of_service | total_amount
------|---------------------|-------------
12    | EB                  | 1000
12    | EB                  | 1200
12    | DG                  | 1500
12    | DG                  | 2000

我能做的是

month | category_of_service | total_amount
------|---------------------|-------------
12    | EB                  | 5700
12    | DG                  | 5700

我真正想要的是

month | category_of_service | total_amount
------|---------------------|-------------
12    | EB                  | 2200
12    | DG                  | 3500

注意:有多个monthscategory_of_services

我正在使用的查询是:

SELECT 
    month, category_of_service, SUM(total_amount) AS TotalAmount
FROM  
    dbo.report
GROUP BY 
    month, category_of_service

以下是我输出的屏幕截图:

enter image description here

1 个答案:

答案 0 :(得分:0)

 ;With Cte([month] , category_of_service , total_amount)
AS
(
SELECT 12    , 'EB', 1000 Union all
SELECT 12    , 'EB', 1200 Union all
SELECT 12    , 'DG', 1500 Union all
SELECT 12    , 'DG', 2000 
)
, Result
AS
(
SELECT * ,ROW_NUMBER()OVER(PARTITION by total_amount ORDER BY [month] desc)  AS Seq FROM
(
SELECT [month] , category_of_service ,Sum(total_amount)OVER(PARTITION BY [month],category_of_service ORDER BY [month])AS total_amount  FROM Cte
)dt
)
SELECT [month] , category_of_service , total_amount FROM Result WHERE seq=1

输出

month | category_of_service | total_amount
------|---------------------|-------------
12    | EB                  | 2200
12    | DG                  | 3500