每天选择相同的值计数

Bal*_*eth 1 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');
Run Code Online (Sandbox Code Playgroud)

我想看看按created日期分组的不同类型的出现次数.

如果我运行类似的东西

select created, type, count(type)
from message
group by created, type
order by created
Run Code Online (Sandbox Code Playgroud)

我明白了

created         type    count
April, 16 2014  hello   2
April, 16 2014  login   2
April, 17 2014  login   4
April, 17 2014  hello   2
Run Code Online (Sandbox Code Playgroud)

我想拥有的是

created         hello   login
April, 16 2014  2       2
April, 17 2014  2       4
Run Code Online (Sandbox Code Playgroud)

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

art*_*rtm 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
Run Code Online (Sandbox Code Playgroud)

更新:

来自@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;
Run Code Online (Sandbox Code Playgroud)

  • 您还可以为Postgresql 9.4添加更清晰的版本:`select created,count(*)filter(where type ='hello')AS hello,count(*)filter(where type ='login')AS login from消息组按创建的顺序创建;` (3认同)