gpt4 book ai didi

sql - 每天选择相同的值计数

转载 作者:行者123 更新时间:2023-11-29 12:33:07 25 4
gpt4 key购买 nike

我有一个类似这样的表:

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');

我想查看按创建 日期分组的不同类型的出现情况。

如果我运行类似的东西

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。感谢您的帮助。

最佳答案

尝试

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 的 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;

关于sql - 每天选择相同的值计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29699204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com