我有这个问题:
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
但我只需要 last 总和。我不需要 in-report sum's
那么如何获得欲望的结果?
(我无法更改group by
条款,因为其他人也需要它,我只想在最后添加和/不加汇总。)
答案 0 :(得分:32)
可以使用GROUPING SETS
,试试这个:
SELECT Name,datee,SUM (val)
FROM @t
GROUP BY
GROUPING SETS((NAME ,datee), ())
答案 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
或者您可以使用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
)
结果是:
| 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
)
)