SQL:将汇总数据组织为两列

时间:2015-04-16 21:08:32

标签: sql postgresql pivot aggregate-filter

我们假设我有一个数据集:

DATE        PAGE_ID  HITS
2014-1-1    1        100
2014-1-1    2        50
2014-1-1    3        20
2014-1-2    1        20
2014-1-2    2        40
2014-1-2    3        20

我目前可以使用:

SELECT date, hits
FROM my_table
WHERE PAGE_ID = 1
GROUP BY date
ORDER BY date ASC

获取1 page_id的每日统计信息。

但是如何获取页面的日期聚合,但是在不同的列中呢?像这样:

DATE        Page_1_hits   All_other_pages
2014-1-1    100             70
2014-1-2    20              60

1 个答案:

答案 0 :(得分:2)

目前的Postgres版本(9.4)

select date, 
       sum(hits) filter (where page_id = 1) as page_1_hits,
       sum(hits) filter (where page_id <> 1) as all_other_pages
from my_table
group by date
order by date asc;

对于早期版本,您需要使用case

select date, 
       sum(case when page_id = 1 then hits end) as page_1_hits,
       sum(case when page_id <> 1 then hits end) as all_other_pages
from my_table
group by date
order by date asc;