postgresql - Postgresql如何在同一个表中使用联合进行两个选择?
问题描述
我有一张桌子:
ID | created_at | 作者 |
---|---|---|
1 | 02.02.2020 | 经理 |
2 | 02.02.2020 | 客户 |
3 | 02.02.2020 | 经理 |
我想得到如下结果,并且日期排序:
日期 | 经理 | 客户 |
---|---|---|
02.02.2020 | 2 | 1 |
03.02.2020 | 5 | 3 |
我试过了:
SELECT created_at::date, count(id) AS manager FROM orders where author = 'manager' GROUP BY created_at::date
union
SELECT created_at::date, count(id) AS client FROM orders where author = 'client' GROUP BY created_at::date
我得到了:
日期 | 经理 |
---|---|
03.02.2020 | 2 |
02.02.2020 | 5 |
解决方案
您不需要联合,这可以使用过滤聚合在单个查询中完成:
select created_at::date,
count(*) filter (where author = 'manager') as managers,
count(*) filter (where author = 'client') as clients
from orders
group by created_at::date
order by created_at::date
推荐阅读
- r - 生成新的唯一 ID 号,同时排除 R 中先前生成的 ID 号
- node.js - child_process.spawnSync() 中的 ENOENT 错误
- firebase - 运行 Firebase 模拟器时 GCLOUD_PROJECT 的值是多少?
- filesystems - FAT32最大分区大小和fat table大小?
- node.js - Vue.js + eslint。错误解析错误:意外的令牌@
- python - 文本文件中的 ANSI 转义颜色代码无法正确打印
- coq - 如何使用 ssreflect 序数索引元组
- c# - 是否可以在没有 Windows 商店且没有旁加载的情况下安装经过微软认证的 appx?
- r - 为超过 100% 的值调整风险表
- python - 在 Pandas 中将两行折叠为 1