Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何按日期计数枚举和分组_Sql_Postgresql - Fatal编程技术网

Sql 如何按日期计数枚举和分组

Sql 如何按日期计数枚举和分组,sql,postgresql,Sql,Postgresql,我有一个表,它有一个日期列和一个用户类型列。如何获得按日期分组的用户类型计数 表-用户日期 Date user_type 期望结果 Date Customer Sales 09/20/2020 2 2 09/21/2020 1 1 在标准SQL中,您可以使用: select date, sum(case when user_type = 'Sales' then 1 else 0 end) as sales

我有一个表,它有一个日期列和一个用户类型列。如何获得按日期分组的用户类型计数

表-用户日期

Date         user_type

期望结果

Date        Customer Sales
09/20/2020   2         2
09/21/2020   1         1

在标准SQL中,您可以使用:

select date,
       sum(case when user_type = 'Sales' then 1 else 0 end) as sales,
       sum(case when user_type = 'Customer' then 1 else 0 end) as customer
from t
group by date;
这是几乎所有数据库都支持的标准语法。有些数据库有快捷方式

在Postgres中,我会这样说:

select date,
       count(*) filter (where user_type = 'Sales') as sales,
       count(*) filter (where user_type = 'Customer') as customer
from t
group by date;

我删除了不一致的数据库标记。请标记您真正使用的数据库。这正是我想要的。非常感谢,戈登。
select date,
       count(*) filter (where user_type = 'Sales') as sales,
       count(*) filter (where user_type = 'Customer') as customer
from t
group by date;