2015-04-15 46 views
3

我對SQL沒有那麼強大,並且需要一些幫助來弄清楚如何獲得記錄集中返回的數字。SQL - 如何SUM GROUP BY記錄集?

這是我在多大程度上與查詢到目前爲止得到:

SELECT DATEDIFF(m, originalretaildate, getdate()) AS age_in_months, count(email) AS number_of_valid_emails 
FROM #result2 
WHERE originalretaildate BETWEEN '20140415' AND GETDATE() 
GROUP BY DATEDIFF(m, originalretaildate, getdate()) 
ORDER BY 1 

這給了我下面的結果:

age_in_months  number_of_valid_emails 
----------------------------- 
0     63 
1     2066 
2     1528 
3     2449 
4     1882 
5     1835 
6     1772 
7     2190 
8     2321 
9     2172 
10     2635 
11     1336 
12     601 

我需要得到的是一個總和(總)所有這些數字。我很樂意把它放在底部,或者甚至只是一個數字返回。

因此,像這樣:

age_in_months  number_of_valid_emails 
----------------------------- 
0     63 
1     2066 
...     ... 
SUM     2129 

任何幫助將非常感激。


它到達那裏,我的SQL查詢現在看起來是這樣的:

SELECT DATEDIFF(m, originalretaildate, getdate()) AS age_in_months, 
count(email) AS number_of_valid_emails 
FROM #result2 
WHERE originalretaildate BETWEEN '20140415' AND GETDATE() 
GROUP BY DATEDIFF(m, originalretaildate, getdate()) WITH ROLLUP 
ORDER BY 2 ASC 

這給了我這樣的:

0 65 
-------- 
12 598 
11 1329 
2 1530 
6 1777 
5 1830 
4 1875 
1 2049 
9 2176 
7 2200 
8 2319 
3 2442 
10 2631 
NULL 22821 

我現在的問題是,它說, 'NULL' 的最後一行。任何想法如何解決這個問題,所以它說'總'或'總和'?

+0

如何像' WITH()AS Q1選擇*從Q1聯盟所有選擇'SUM',SUM(number_of_valid_emails)FROM Q1'? – Turophile

+0

@louism看到編輯 –

回答

3

根據我的理解,你想總結底部的值。您可以使用匯總獲取底部值的總和。

SELECT DATEDIFF(m, originalretaildate, getdate()) AS age_in_months, 
count(email) AS number_of_valid_emails 
FROM #result2 
WHERE originalretaildate BETWEEN '20140415' AND GETDATE() 
GROUP BY DATEDIFF(m, originalretaildate, getdate()) with rollup 
ORDER BY 1 

它會產生像波紋管一樣的輸出。在所有的總和底部值

age_in_months  number_of_valid_emails 
----------------------------- 
0     63 
1     2066 
2     1528 
3     2449 
4     1882 
5     1835 
6     1772 
7     2190 
8     2321 
9     2172 
10     2635 
11     1336 
12     601 

null    22850 

編輯1

按照您的編輯,你可以使用COALESCE這樣

SELECT COALESCE(DATEDIFF(m, originalretaildate, getdate()),'Total') AS age_in_months, 
count(email) AS number_of_valid_emails 
FROM #result2 
WHERE originalretaildate BETWEEN '20140415' AND GETDATE() 
GROUP BY DATEDIFF(m, originalretaildate, getdate()) with rollup 
ORDER BY 1 

編輯做2

使用投射到您的monthnumber然後用coalesce()功能,所以這將是能夠施展它在適當的方式

cast(DATEDIFF(m, originalretaildate, getdate()) as nvarchar(10)) 

整個查詢會是這樣的

SELECT COALESCE(cast(DATEDIFF(m, originalretaildate, getdate()) as nvarchar(10)),'Total') AS age_in_months, 
count(email) AS number_of_valid_emails 
FROM #result2 
WHERE originalretaildate BETWEEN '20140415' AND GETDATE() 
GROUP BY DATEDIFF(m, originalretaildate, getdate()) with rollup 
ORDER BY 1 
+2

一旦你'訂購1','NULL'會出現在頂部。你可以使用'ORDER BY(age_in_months * -1)DESC'來訂購 – ughai

+0

@ughai是的你是對的。感謝您的糾正 –

+1

就是這樣,你是一個王子阿穆亞斯男子阿梅亞。我希望我知道這樣的SQL,非常有用。 – louism