带过滤列的PostgreSQL视图

时间:2017-05-26 06:44:53

标签: postgresql

我有一张这样的桌子:

date_added        owner        action
01-02-2016        1            note
04-02-2016        1            call
04-02-2016        1            call
05-02-2016        1            note
05-02-2016        1            meeting
06-02-2016        1            meeting
06-02-2016        1            note
06-02-2016        1            cal
06-02-2016        1            note
10-02-2016        1            call
10-02-2016        1            note
10-02-2016        1            meeting

我需要这样的观点:

date_added        owner        note        call        meeting
01-02-2016        1            1           0           0
04-02-2016        1            0           2           0
05-02-2016        1            0           0           1
06-02-2016        1            2           1           1
10-02-2016        1            1           1           1

如何使用

之类的内容创建列
WHERE action LIKE 'note'

1 个答案:

答案 0 :(得分:2)

您可以使用CASE表达式。

<强>查询

select date_added, owner,
sum(case action when 'note' then 1 else 0 end) note,
sum(case action when 'call' then 1 else 0 end) call,
sum(case action when 'meeting' then 1 else 0 end) meeting
from your_table_name
group by date_added, owner;

<强> Find demo here