2

我有一个存储过程,它为每个返回一组行ActivityUnitId

需要的是基于小时数的每个 ActivityUnitId 的前 10 行。我设法实现了这一点,我的查询看起来像

With Data AS
(SELECT  
   ProjectID,ActivityUnitID,Description,GroupID,
   SUM(Hours) AS NoiseHours,
   ROW_NUMBER() OVER(PARTITION BY ActivityUnitID ORDER BY SUM(Hours) DESC) as 'RowNum'
FROM         
   tbl_Sub 
INNER JOIN
   tbl_AnalysisData ON tbl_Sub.SubActivityID = tbl_AnalysisData.SubActivityID 
     INNER JOIN
       tbl_Analysis ON tbl_AnalysisData.LookupID = tbl_Analysis.LookupID
         INNER JOIN
           tbl_ActivityUnit ON tbl_ActivityUnit.ActivityUnitID = tbl_Sub.ActivityUnitID
           tbl_Suby.ProjectID = @ProjectID 
         AND
           tbl_Sub.ActivityUnitID = ISNULL(@ActivityUnitID,tbl_Sub.ActivityUnitID)
GROUP BY 
  ActivityUnitID,ProjectID,  Description,AUGroupID
) SELECT * from Data where RowNum<=10

“RowNum”列包含每行的行号,其值已根据小时数分配。所以前 10 行包含前 10 小时的行。

现在我想要的是在每个 ActivityUnitID 的末尾添加一个额外的摘要行。这将包含所有被遗漏的行的小时总和,即 RowNum > 10 的汇总行

所以我最后将得到的是每个 ActivityUnitID 的前 10 行 + 一个额外的行,该行将总结该 ActivityUnitID 的其他行的小时数

例如,假设我有一张有 2 列的表

ID  Hours     RowNum
1A    30         1
2B    20         2
3C    10         3
4D     5         4
5E     4         5
6F     3         6

如何对此进行选择,以便获得 RowNum <=3 的行和其他行的总和

ID  Hours  
1A   30
2B   20
3C   10
Oth  12
4

1 回答 1

3

最简单的方法是UNION使用您已经拥有的数据进行总计

SELECT  NULL, NULL, 'Totals', NULL, SUM(NoiseHours), 11 AS RowNumber
FROM    Data 
WHERE   RowNum > 10

你的完整陈述可能看起来像这样

With Data AS
(
SELECT  ProjectID,ActivityUnitID,Description,GroupID,
        SUM(Hours) AS NoiseHours,
        ROW_NUMBER() OVER(PARTITION BY ActivityUnitID ORDER BY SUM(Hours) DESC) as 'RowNum'
FROM         tbl_Sub 
            INNER JOIN
            tbl_AnalysisData ON tbl_Sub.SubActivityID = tbl_AnalysisData.SubActivityID 
            INNER JOIN
            tbl_Analysis ON tbl_AnalysisData.LookupID = tbl_Analysis.LookupID
            INNER JOIN
            tbl_ActivityUnit ON tbl_ActivityUnit.ActivityUnitID = tbl_Sub.ActivityUnitID
tbl_Suby.ProjectID = @ProjectID 
AND
tbl_Sub.ActivityUnitID = ISNULL(@ActivityUnitID,tbl_Sub.ActivityUnitID)
GROUP BY ActivityUnitID,ProjectID,  Description,AUGroupID
)
SELECT * from Data where RowNum<=10
UNION ALL 
SELECT  NULL, NULL, 'Totals', NULL, SUM(NoiseHours), 11 AS RowNumber
FROM    Data 
WHERE   RowNum > 10

使用联合的困难在于联合的两个部分应该具有相同数量和相同类型的列,因此需要在选择中添加虚拟列。

于 2012-10-29T05:41:30.560 回答