postgresql:从纪元时间开始按年份和月份进行选择

时间:2017-05-14 08:24:58

标签: postgresql

我需要从postgresql db获取输出,如下所示:

2016     十一月     十二月   2017年     一月     二月     月

我一直在谷歌搜索,测试,玩,但还没有接近。 所以我告诉你们那些会告诉我我是谁的人! 我知道如何在mysql中做到这一点,但postgres没有。

哦,是的,这是Postgres 9.6。

1 个答案:

答案 0 :(得分:0)

不确定,但可能你需要这个吗?

with your_table(dt) as(
    select '2016-11-01'::date union all
    select '2016-11-02'::date union all
    select '2016-12-01'::date union all
    select '2017-01-01'::date union all
    select '2017-02-01'::date union all
    select '2017-02-02'::date union all
    select '2017-03-01'::date union all
    select '2017-10-01'::date union all
    select '2017-11-01'::date union all
    select '2018-02-01'::date  
)

-- Above is just table simulation, actual query is below:

select case when month_name is null then y::text else month_name end from (
    select extract(year from dt) as y, 0 as month_number, null as month_name   from your_table group by extract(year from dt)
    union all
    select extract(year from dt), extract(month from dt) as month_number, '--'||to_char(min(dt), 'Mon') as month_name from your_table
    group by extract(year from dt), extract(month from dt)
) t
order by y, month_number