2010-11-16 68 views
1

我有這個形式的查詢:SQL多個組 - 可能嗎?

SELECT e.date, SUM(e.size) as bytes 
FROM entries AS e 
GROUP BY e.date 
ORDER BY bytes DESC 

,我有一個名爲客戶端柱,它是由靜態值(0,1,2,3),所以我希望得到這樣的:

SELECT e.date, SUM(e.size) as bytes 
FROM entries AS e 
WHERE e.client = 0 
GROUP BY e.date 
ORDER BY bytes DESC 

重複爲每個客戶端類型,但在一個單一的查詢來獲取每一個客戶端類型彙總尺寸的結果:

DATE | CLI0-SIZE | CLI1-SIZE | CLI2-SIZE | CLI3-SIZE 
2010-11-11  113   344   435   155 
+0

您正在使用哪個數據庫? – 2010-11-16 23:28:25

回答

7

你可以試試這個

SELECT e.date, 
    SUM(CASE WHEN e.client = 0 THEN e.size ELSE 0 END) as CLI0-SIZE, 
    SUM(CASE WHEN e.client = 1 THEN e.size ELSE 0 END) as CLI1-SIZE, 
    SUM(CASE WHEN e.client = 2 THEN e.size ELSE 0 END) as CLI2-SIZE, 
    SUM(CASE WHEN e.client = 3 THEN e.size ELSE 0 END) as CLI3-SIZE 
FROM entries AS e 
GROUP BY e.date 
+0

..........好的! – einundswanzig 2010-11-17 16:02:51

1

關係數據庫管理系統:Microsoft SQL Server的

這將返回以下佈局:

date | client | bytes 
2010-11-11 | 2 | 435 
2010-11-11 | 1 | 344 
2010-11-11 | 3 | 155 
2010-11-11 | 0 | 113 

這將組的所有客戶端類型,而不僅僅是0,1,2,3 - 我想你想要這個。

SELECT 
    e.date, 
    e.client, 
    SUM(e.size) AS bytes 
FROM 
    entries AS e 
GROUP BY 
    e.date, 
    e.client 
ORDER BY 
    bytes DESC 

然後,您可以在桌子上執行數據透視。

+0

不是我一直在尋找,但至少它在一個查詢中獲取我的信息。 – einundswanzig 2010-11-17 15:57:20