与ROLLUP GRAND TOTAL和SUBTOTAL

时间:2013-11-22 01:02:59

标签: sql sql-server null rollup

我有一个脚本可以生成几乎存在的结果集!我正试图获得小计和总计。我在年份列上得到小计,在最后得到总计。我的目标是让最终结果表示“总计”而不是小计。请注意,由于汇总功能,我的最后一行“location”也会返回null。

SELECT
  YEAR,
  COUNT(ACCOUNTS) AS 'ACCOUNTS',        
  SUM(BALANCE) as 'BAL',
  LOCATION AS 'LOCATION'
FROM 
  ACCOUNT A 
WHERE C.CREATE BETWEEN 
  DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()-1),0) 
  AND DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()),0)
GROUP BY 
  LOCATION, YEAR
WITH ROLLUP

结果集......

YEAR  ACCOUNTS  BAL        LOCATION
----  --------  ---------  --------
NULL        11   80687.51  WA
NULL       107  592980.18  NULL

期望的结果集......

YEAR          ACCOUNTS  BAL        LOCATION
----          --------  ---------  --------
sub total           11   80687.51  WA
grand total        107  592980.18  ALL

2 个答案:

答案 0 :(得分:1)

您可以使用GROUPING_ID来识别每行聚合的分组集

SELECT
   CASE GROUPING_ID(LOCATION, YEAR)
     WHEN 0 THEN YEAR
     WHEN 2 THEN N'Sub total: ' + STR(YEAR) 
     WHEN 3 THEN N'Grand total'
  END
   COUNT(ACCOUNTS) AS 'ACCOUNTS',      
   SUM(BALANCE) as 'BAL',
   LOCATION AS 'LOCATION'
 FROM ACCOUNT A 
 WHERE C.CREATE BETWEEN DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()-1),0) 
                    AND DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()),0)
 GROUP BY LOCATION, YEAR
 WITH ROLLUP

答案 1 :(得分:1)

你需要使用CASE WHEN(GROUPING(ColumnName)= 1),如下所示:

SELECT
  CASE WHEN GROUPING(YEAR) = 1 AND GROUPING(LOCATION) = 1 THEN 'grand total'
       WHEN GROUPING(YEAR) = 1 AND GROUPING(LOCATION) <> 1 THEN 'sub total'
       ELSE YEAR END AS YEAR
  COUNT(ACCOUNTS) AS 'ACCOUNTS',        
  SUM(BALANCE) as 'BAL',
  CASE WHEN GROUPING(LOCATION) = 1 THEN 'ALL' ELSE LOCATION AS 'LOCATION'
FROM 
  ACCOUNT A 
WHERE C.CREATE BETWEEN 
  DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()-1),0) 
  AND DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()),0)
GROUP BY 
  LOCATION, YEAR
WITH ROLLUP