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



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

2016年 11 月 12 月 2017 一月 2月 三月

我一直在谷歌搜索,测试,玩,但还没有接近。所以我向你们嘟,他们会告诉我我是什么诺德!我确实知道如何在 mysql 中执行此操作,但没有。

哦,是的,它是Postgres 9.6。

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

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

最新更新