Fill in missing rows when aggregating over multiple fields in Postgres

后端 未结 2 1413
温柔的废话
温柔的废话 2021-01-18 08:35

I am aggregating sales for a set of products per day using Postgres and need to know not just when sales do happen, but also when they do not for further processing.

2条回答
  •  自闭症患者
    2021-01-18 09:05

    select 
        date, 
        count(sale_id) as sales, 
        product
    from
        sales_data
        right join (
            (
                select d::date as date
                from generate_series (
                    (select min(date) from sales_data),
                    (select max(date) from sales_data),
                    '1 day'
                ) gs (d)
            ) gs
            cross join
            (select distinct product from sales_data) p
        ) cj using (product, date)
    group by product, date
    order by product, date
    

提交回复
热议问题