SQLite:多个聚合列

时间:2014-01-07 14:14:38

标签: sql sqlite aggregate-functions

我对SQL世界有点新鲜,仍在学习该语言的细节。

我有一张带有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
...

希望有助于澄清我之后的事情。

2 个答案:

答案 0 :(得分:1)

以下是详细的,但应该可以工作(通用ideone sql demo不幸的是,SqlFiddle上的Sqlite目前已关闭):

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;

答案 1 :(得分:0)

SELECT dayOfWeek, sum(numEvents) as numberOfEvents
FROM t
GROUP BY dayOfWeek;