SQL:将求和数据组织成两列

SQL: Organizing summed data into two columns

假设我有一个像这样的数据集:

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

对于当前的 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;