2013-01-23 37 views
14

我有這個疑問:與SQL服務器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

但我只需要最後總和線。我不需要報告中sum's

那麼如何得到慾望的結果呢?

(我不能改變group by子句導致其他人也需要它,我只是想在最後加總和/不加總和)。

sql online is here

回答

27

這可能與GROUPING SETS,試試這個:

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

SQL Fiddle

+0

@RoyiNamir不客氣,這是一個標準的TSQL功能,但它沒有經常使用(我猜),所以人們並不總是知道關於它:) –

+0

我真的需要閱讀有關它。 –

+0

@RoyiNamir我相信你會在網上找到關於它的資源,我在一本書中讀到它(儘管我不記得使用它)。 –

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 | 
+0

FYI @t是查詢的結果。 (沒關係),所以生病必須寫兩遍。我確實嘗試過使用CTE,但是:http://i.stack.imgur.com/hYhOk。jpg –

+0

@RoyiNamir那麼第二個,應該工作,因爲沒有工會所有 – Taryn

9

也可以與ROLLUP()

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

WITH ROLLUP以及WITH CUBE是非標準的,並且已被棄用。 (見不符合ISO標準的語法GROUP BY手冊。)

應當指出的是,ROLLUP()不兼容級別在SQL Server 2005或下在SQL Server 2008+ 100支持下,90,而GROUPING SETS()是。

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 
      ) 
     )