SQL查询以获取按另一列分组的值的总和

时间:2016-10-24 15:56:43

标签: sql-server tsql sql-server-2012 group-by

我有这样的结果:

enter image description here

我目前使用的查询是:

SELECT TOP 1000 [FundReportLoanDataID]
      ,[SegAmortisation]
      ,frlc.FundReportCategoryId,
      SUM(CurrentLB) AS '% of Fund'
  FROM [dbo].[FundReportLoanData] frld
  INNER JOIN [dbo].[FundReportCategories] frlc
  ON frld.SegAmortisation = frlc.Description
    group by frlc.FundReportCategoryId, frld.SegAmortisation, frld.FundReportLoanDataID, frld.LoanId, frld.CurrentLB

正如您所看到的,虽然我正在通过FundReportCategoryId进行分组,但是有多个具有相同ID的结果,但我希望所有这些结果都基于FundReportCategoryId放入一个总和结果中。

为了达到我想要的目的,我需要改变什么?

3 个答案:

答案 0 :(得分:0)

您尝试汇总CurrentLB并在Group by中添加了相同的列,这也是重复的原因。从frld.CurrentLB

中删除Group by

此外,您需要从FundReportLoanDataIDSELECT移除group by,因为每行的数据看起来都是唯一的。

...
group by frld.SegAmortisation, 
         frld.FundReportLoanDataID

也从frld.LoanId删除Group By因为您没有选择它也可能是重复的原因

答案 1 :(得分:0)

如果我理解正确,您正在寻找每个FundReportCategoryId的百分比。如果是这样,您可以使用窗口函数

SELECT TOP 1000 [FundReportLoanDataID]
      ,[SegAmortisation]
      ,frlc.FundReportCategoryId,
      SUM(CurrentLB)/SUM(CurrentLB) OVER(PARTITION BY frlc.FundReportCategoryId ) AS '% of Fund'
  FROM [dbo].[FundReportLoanData] frld
  INNER JOIN [dbo].[FundReportCategories] frlc
  ON frld.SegAmortisation = frlc.Description
  group by frlc.FundReportCategoryId, frld.SegAmortisation, frld.FundReportLoanDataID, frld.LoanId, frld.CurrentLB

答案 2 :(得分:0)

尝试一下

    SELECT TOP 1000 
        [SegAmortisation],
        frlc.FundReportCategoryId,
        SUM(CurrentLB) AS '% of Fund'
    FROM [dbo].[FundReportLoanData] frld
    INNER JOIN [dbo].[FundReportCategories] frlc
        ON frld.SegAmortisation = frlc.Description
    GROUP BY frld.SegAmortisation, frlc.FundReportCategoryId

下次请提供您想要的输出:)