2014-01-07 85 views
2

我對SQL世界有點新,但仍然在學習語言的細節。SQLite:多個聚合列

我有一張桌子,上面有id,dayOfWeek和每天的計數。因此,任何給定的ID可能會出現在表中多達七次,每個ID每天的事件計數。我想重組該表爲每個ID的單行一週的每一天一列,像下面的顯然是不正確的查詢的東西:

SELECT id, sum(numEvents where dayOfWeek = 0), sum(numEvents where dayOfWeek = 1) ... from t; 

有沒有解決這個堅實的方式?

編輯:

我擔心我可能不是很清楚。該表將理想的結構是這樣的:

id | Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday 
0 | 13  | 45  | 142  | 3   | 36  | 63  | 15336 
1 | 17  | 25  | 45  | 364  | 37  | 540 | 0 

所以事件0出現13次在週日,45日(星期一)等等......我現在的表看起來像這樣:

id | dayOfWeek | count 
0 | 0   | 13 
0 | 1   | 45 
0 | 2   | 142 
0 | 3   | 3 
0 | 4   | 36 
0 | 5   | 63 
0 | 6   | 15336 
1 | 0   | 17 
1 | 1   | 25 
... 

。希望有助於清理我以後的事情。

回答

1

以下是詳細,但應該工作(通用ideone sql demo不幸SqlLite上SqlFiddle是下降的時刻):

SELECT id, 
    SUM(case when dayofweek = 1 then numevents else 0 end) as Day1Events, 
    SUM(case when dayofweek = 2 then numevents else 0 end) as Day2Events, 
    SUM(case when dayofweek = 3 then numevents else 0 end) as Day3Events 
     --, etc... 
FROM EventTable 
GROUP BY ID; 
0
SELECT dayOfWeek, sum(numEvents) as numberOfEvents 
FROM t 
GROUP BY dayOfWeek;