如何在PostgreSQL中的一行中获取多个值?

时间:2019-01-02 10:17:08

标签: sql postgresql-9.4

我在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     |    

2 个答案:

答案 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