23

我有这个查询:

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 

目前的结果是:

在此处输入图像描述

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

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

在此处输入图像描述

但我只需要最后一个总和行。我不需要内报告 sum's

那么如何才能得到想要的结果呢?

(我不能更改 group by子句,因为其他人也需要它,我只想在最后加上/不加总和)。

sql在线就在这里

4

4 回答 4

41

有可能GROUPING SETS,试试这个:

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

SQL小提琴

于 2013-01-23T11:27:32.033 回答
12

也可以ROLLUP()

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

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

需要注意的ROLLUP()是,在 SQL Server 2005 的 90 以下或 SQL Server 2008+ 的 100 以下的兼容性级别不支持,而支持GROUPING SETS()

于 2013-01-23T12:36:49.827 回答
4

如果你只想要最终的总数,你不能只使用 a UNION ALL

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

请参阅带有演示的 SQL Fiddle

或者您可以使用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

结果是:

|   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 |
于 2013-01-23T11:19:14.010 回答
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
             )
        )
于 2013-08-01T07:24:10.190 回答