2013-06-19 100 views
8

Hy。有在我的PostgreSQL數據庫類似Group by on Postgresql日期時間

CODE  DATE  COUNT 
"3443" "2009-04-02" 3 
"3444" "2009-04-06" 1 
"3443" "2009-04-06" 1 
"3443" "2009-04-07" 7 

員工記錄我想用一個查詢「選擇所有代碼並計數發生在本月」

結果:

CODE  DATE  COUNT 
"3443" "2009-04" 3 
"3441" "2009-04" 13 
"3442" "2009-04" 11 
"3445" "2009-04" 72 

我確實使用查詢即

SELECT CODE,date_part('month',DATE),count(CODE) 
FROM employee 
where 
group by CODE,DATE 

以上查詢運行良好,但列出的月份我記錄以數字的形式出現,很難發現一個月屬於哪一年。總之,我希望得到結果,就像上面在RESULT部分提到的一樣。由於

回答

17

試試這個:

SELECT CODE, to_char(DATE, 'YYYY-MM'), count(CODE) 
FROM employee 
where 
group by CODE, to_char(DATE, 'YYYY-MM') 
1

嘗試任何的

SELECT CODE,count(CODE), 
    DATE as date_normal, 
    date_part('year', DATE) as year, 
    date_part('month', DATE) as month, 
    to_timestamp(
     date_part('year', DATE)::text 
     || date_part('month', DATE)::text, 'YYYYMM') 
     as date_month 
FROM employee 
where 
group by CODE,DATE; 
12

根據您是否想要的結果爲文本或日期,你也可以寫這樣的:

SELECT CODE, date_trunc('month', DATE), COUNT(*) 
    FROM employee 
    GROUP BY CODE, date_trunc('month', DATE); 

哪個在你的榜樣會回到這一點,與日期仍然是一個時間戳,如果你打算做進一步可以是有用的因爲沒有轉換它的計算是必要的:

CODE  DATE  COUNT 
"3443" "2009-04-01" 3 
"3441" "2009-04-01" 13 
"3442" "2009-04-01" 11 
"3445" "2009-04-01" 72 

date_trunc()也接受其他值,例如quarteryear等 見documentation所有值