我在postgreSQL9.4中有数据库表名称emp_leave,例如
|emp_name|leave_type|total_lday|
| Tame | PL | 3 |
| Tame | UL | 4 |
我想要类似的查询结果
|emp_name|paid_leave|unpaid_leave|
| Tame | 3 | 4 |
答案 0 :(得分:7)
Postgresql 9.4还具有FILTER
子句以进行条件聚合:
select emp_name,
max(total_lday) FILTER (where leave_type = 'PL') as paid_leave,
max(total_lday) FILTER (where leave_type = 'UL') as unpaid_leave
from emp_leave
group by emp_name
(ANSI SQL-2016,功能T612,“高级OLAP操作”。)
答案 1 :(得分:3)
您可以在下面尝试-使用条件聚合
select emp_name,
max(case when leave_type='PL' then total_lday end) as paid_leave,
max(case when leave_type='UL' then total_lday end) as unpaid_leave
from emp_leave
group by emp_name