2015-04-16 13 views
0

比方說,我有這樣一個數據集:SQL:組織相加後的數據爲兩列

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 

回答

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; 
+0

。 。你知道使用'filter'子句有什麼好處嗎?它是否在未來的ANSI SQL版本中? –

+0

順便說一句有上述一個錯字,應該說「當命中結束」而不是「母雞命中結束」 – LittleBobbyTables

+2

@GordonLinoff:這不是一個「未來」 SQL標準。這是我認爲它是在SQL:2003標準中引入的_current_ SQL標準。我認爲在「記錄」你的意圖方面有點清晰。至少在這篇博客中,它似乎也更快:http://www.cybertec.at/postgresql-9-4-aggregation-filters-他們做的回報/ –