【问题标题】:SQL Server : Group by two columns and Sum a third column with the bifurcation of two groupsSQL Server:按两列分组,并将第三列与两组的分叉相加
【发布时间】:2017-04-24 09:23:02
【问题描述】:

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

到目前为止,我可以根据两个过滤器使用 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

【问题讨论】:

  • 您发布的查询无法返回5700,它将是您想要的结果。
  • @Shubham Katta 您发布的查询是正确的查询,除非您错过在查询中写入 category_of_service
  • 您的查询 100% 正确
  • 但我得到的输出与查询不符。@dnoeth
  • 我也分享了相关图片

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


【解决方案1】:
 ;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

【讨论】:

  • 为了提高您回答的质量,请说明是什么导致提问者出现问题,它是如何做到的,以及您的回答如何解决问题.
猜你喜欢
  • 2022-11-12
  • 2018-11-29
  • 2021-12-04
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 2019-01-13
相关资源
最近更新 更多