来自YYYYMMDD int列的YYYYMM分组 - Postgresql

时间:2017-02-09 16:59:35

标签: postgresql

我在yyyymmdd格式的int列中有日期,我想按月分组,即yyyymm。我尝试了以下两个版本

 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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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;