Postgresql获取一年中的所有月份和空值

时间:2015-11-17 11:38:51

标签: sql postgresql null

我试图在PostgreSQL中进行查询,该查询应该给我一年中所有月份的数据,每月排序一次。以及销售列为空的月份的null值。但是,我无法显示所有月份,也没有null值。请帮帮忙?

这是我的问题:

SELECT
    to_char(date_trunc('Month', dateofmonth), 'Month') MON,
    sum(sales) SALES
FROM SALES_TABLE
GROUP BY MON;

2 个答案:

答案 0 :(得分:3)

您可以使用generate_series()生成一年的月份。然后,您可以使用left join加入聚合中的值。像这样:

select mon.mon, coalesce(s.sales, 0) as sales
from generate_series('2015-01-01'::timestamp, '2015-12-01'::timestamp, interval '1 month'
                    ) as mon(mon) left join
     (select date_trunc('Month', dateofmonth) as mon,
             sum(sales) as SALES
      from  SALES_TABLE
      group by mon
    ) s
    on mon.mon = s.mon;

答案 1 :(得分:0)

with sales_table (sales, dateofmonth) as ( values
    (100, '2015-02-10'::date),(100, '2015-02-15'),(200, '2014-07-10')
), months as (
    select generate_series(min_month, max_month, '1 month') as month
    from (
        select
            date_trunc('year', min(dateofmonth)) as min_month,
            date_trunc('year', max(dateofmonth) + interval '1 year') - interval '1 month' as max_month
        from sales_table
    ) s
)
select
    to_char(date_trunc('month', m.month), 'YYYY Month') mon,
    sum(sales) sales
from
    sales_table st
    right join
    months m on date_trunc('month', st.dateofmonth) = m.month
group by m.month
order by m.month
;
      mon       | sales 
----------------+-------
 2014 January   |      
 2014 February  |      
 2014 March     |      
 2014 April     |      
 2014 May       |      
 2014 June      |      
 2014 July      |   200
 2014 August    |      
 2014 September |      
 2014 October   |      
 2014 November  |      
 2014 December  |      
 2015 January   |      
 2015 February  |   200
 2015 March     |      
 2015 April     |      
 2015 May       |      
 2015 June      |      
 2015 July      |      
 2015 August    |      
 2015 September |      
 2015 October   |      
 2015 November  |      
 2015 December  |