每天选择相同的值计数

时间:2015-04-17 12:26:38

标签: sql postgresql

我有一张类似的表:

CREATE TABLE message(id int, type varchar(100), created timestamp);

insert into message (id, type, created) values (1, 'hello', '2014-04-16');
insert into message (id, type, created) values (2, 'hello', '2014-04-16');
insert into message (id, type, created) values (3, 'login', '2014-04-16');
insert into message (id, type, created) values (4, 'login', '2014-04-16');
insert into message (id, type, created) values (5, 'hello', '2014-04-17');
insert into message (id, type, created) values (6, 'hello', '2014-04-17');
insert into message (id, type, created) values (7, 'login', '2014-04-17');                     
insert into message (id, type, created) values (8, 'login', '2014-04-17');
insert into message (id, type, created) values (9, 'login', '2014-04-17');
insert into message (id, type, created) values (10, 'login', '2014-04-17');

我希望看到按created日期分组的不同类型的出现次数。

如果我运行类似

的话
select created, type, count(type)
from message
group by created, type
order by created

我得到了

created         type    count
April, 16 2014  hello   2
April, 16 2014  login   2
April, 17 2014  login   4
April, 17 2014  hello   2

我想拥有的是

created         hello   login
April, 16 2014  2       2
April, 17 2014  2       4

我正在使用PostgreSQL 9.3。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:5)

尝试

select created, count(case type when 'hello' then 1 else null end) AS hello,
count(case type when 'login' then 1 else null end) AS login
from message
group by created
order by created

<强>更新

来自@SamiKuhmonen for Postgresql 9.4

select created, 
    count(*) filter (where type='hello') AS hello, 
    count(*) filter (where type='login') AS login 
from message 
group by created 
order by created;