与SQL服务器RollUP相加 - 但只是最后一个摘要?

时间:2013-01-23 11:15:40

标签: sql-server sql-server-2008 sum rollup

我有这个问题:

DECLARE @t TABLE(NAME NVARCHAR(MAX),datee date,val money)

insert INTO @t SELECT 'a','2012-01-02',100
insert INTO @t SELECT 'a','2012-01-02',100
insert INTO @t SELECT 'a','2012-01-03',100
insert INTO @t SELECT 'a','2012-01-05',100
insert INTO @t SELECT 'b','2012-01-06',200
insert INTO @t SELECT 'b','2012-01-07',200
insert INTO @t SELECT 'd','2012-01-07',400
insert INTO @t SELECT 'e','2012-01-09',500
insert INTO @t SELECT 'f','2012-01-12',600

SELECT  Name,datee,SUM (val) 
from @t GROUP BY NAME ,datee 

目前的结果是:

enter image description here

但我需要在最后添加sum。 所以我尝试使用汇总:

 SELECT  Name,datee,SUM (val) 
    from @t GROUP BY NAME ,datee  with ROLLUP

enter image description here

但我只需要 last 总和。我不需要 in-report sum's

那么如何获得欲望的结果?

(我无法更改group by条款,因为其他人也需要它,我只想在最后添加和/不加汇总。)

sql online is here

4 个答案:

答案 0 :(得分:32)

可以使用GROUPING SETS,试试这个:

SELECT  Name,datee,SUM (val) 
FROM    @t 
GROUP BY 
        GROUPING SETS((NAME ,datee), ())

SQL Fiddle

答案 1 :(得分:10)

也可以使用ROLLUP()

SELECT
  Name,
  datee,
  SUM (val) 
FROM @t 
GROUP BY 
  ROLLUP((NAME, datee))
;

WITH ROLLUP以及WITH CUBE是非标准的,已弃用。 (请参阅GROUP BY手册中的非ISO标准语法。)

应该注意的是,SQL Server 2005中90以下的兼容级别不支持ROLLUP(),SQL Server 2008+中的兼容级别低于GROUPING SETS(),而{{1}}是。{/ p>

答案 2 :(得分:4)

如果您只想要最终总数,则不能只使用UNION ALL

SELECT  Name,datee,SUM (val) 
from @t 
GROUP BY NAME ,datee 
union all
SELECT  null,null,SUM (val) 
from @t

请参阅SQL Fiddle with Demo

或者您可以使用WHERE子句来过滤具有null值的行:

select name, 
  datee, 
  total
from
(
  SELECT  Name,datee,SUM (val) total
  from @t 
  GROUP BY NAME, datee with rollup
) src
where datee is not null
or
(
  name is null 
  and datee is null
)

请参阅SQL Fiddle with Demo

结果是:

|   NAME |      DATEE | COLUMN_2 |
----------------------------------
|      a | 2012-01-02 |      200 |
|      a | 2012-01-03 |      100 |
|      a | 2012-01-05 |      100 |
|      b | 2012-01-06 |      200 |
|      b | 2012-01-07 |      200 |
|      d | 2012-01-07 |      400 |
|      e | 2012-01-09 |      500 |
|      f | 2012-01-12 |      600 |
| (null) |     (null) |     2300 |

答案 3 :(得分:1)

您可以使用此查询:

SELECT  *
FROM    ( SELECT    Name ,
                    datee ,
                    SUM(val) summ
          FROM      @t
          GROUP BY  NAME ,
                    datee
                    WITH ROLLUP
        ) A
WHERE   ( datee IS NOT NULL
          OR ( datee IS NULL
               AND name IS NULL
             )
        )