2017-02-09 27 views
0

我有YYYYMMDD格式的日期int列,我想按一個月即yyyymm.I've嘗試以下集團從年月日INT列YYYYMM - PostgreSQL的

兩個版本
select to_char(to_timestamp(create_dt),'YYYYMM'),count(*) from table_name 
group by to_char(to_timestamp(create_dt),'YYYYMM') 
order by to_char(to_timestamp(create_dt),'YYYYMM') desc 

select to_char(create_dt,'YYYYMM'),count(*) from table_name 
group by to_char(create_dt,'YYYYMM') 
order by to_char(create_dt,'YYYYMM') desc 
+0

,當你想這些版本發生了什麼? – lurker

+0

@lurker只有1行,您的查詢與我發佈的第二個查詢類似。 「YYYYMM」; 733103965。我將該列轉換爲一個字符串,並使用子字符串以第6個字符進行分組。 –

回答

1
select create_dt/100, count(*) 
from t 
group by 1 
order by 1 desc 
limit 6 
+0

不錯!以下答案有問題嗎? –

+1

@inquisitive_mind沒有錯,只是太冗長。 –

0

想通了,任何替代方法都會有所幫助。

select substring(create_dt::int8,1,6),count(*) from table 
group by substring(create_dt::int8,1,6) 
order by substring(create_dt::int8,1,6) desc 
limit 6; 
+0

你如何規劃int8的substr? - 可能是'substring(create_dt,1,6):: int8'? –