SQL中的摘要行

时间:2012-10-29 05:30:05

标签: sql tsql stored-procedures

我有一个存储过程,为每个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&gt; 10

所以我最终会得到的是每个ActivityUnitID的前十行+一个额外的行,用于总结该ActivityUnitID的其他行的小时数

例如,假设我有一个包含2个列的表

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

我如何对此进行选择,以便获得RowNum&lt; = 3的行和另一行其他行的总和

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

1 个答案:

答案 0 :(得分: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

使用union时的难度是,union的两个部分应该具有相同数量和相同类型的列,因此需要将 dummy 列添加到选择。