如何从PostgresSQL中的一行中获取列数据?

时间:2018-10-26 12:43:30

标签: sql pivot postgresql-9.1

我有数据库表名称工资表,如
| Employee | | Period | | Attributes | | Amount |
| Zakir | | Oct'18 | | Basic | | 20000 |
| Zakir | | Oct'18 | | H.Rent | | 10000 |
| Zakir | | Oct'18 | | Convene | | 2000 |
| Zakir | | Oct'18 | | Medical | | 2000 |
| Tame | | Oct'18 | | Basic | | 30000 |
| Tame | | Oct'18 | | H.Rent | | 15000 |
| Tame | | Oct'18 | | Convene | | 2500 |
| Tame | | Oct'18 | | Medical | | 2500 |

我想要

| Employee | | Period | | Basic | | H.Rent| |Convene| |Medical| |Gross|
| Zakir | | Oct'18 | | 20000 | | 10000 | | 2000 | | 2000 | |34000|
| Tame | | Oct'18 | | 30000 | | 15000 | | 2500 | | 2500 | |50000|

1 个答案:

答案 0 :(得分:1)

用例何时

select employee ,period,
sum(case when attribute='basic' then amount else 0 end) basic,
sum(case when attribute='H.Rent' then amount else 0 end H_Rent,
sum(case when attribute='Convene' then amount else 0 end) Convene,
sum(case when attribute='Medical' then amount else 0 end) Medical,
sum(case when attribute='basic' then amount else 0 end)+
sum(case when attribute='H.Rent' then amount else 0 end)+
sum(case when attribute='Convene' then amount else 0 end)+
sum(case when attribute='Medical' then amount else 0 end) as gross
from payroll group by employee ,period