在SQL

时间:2019-05-31 10:40:09

标签: sql postgresql

我有一个表“ Total Product”,其中某些行之一的总积为NULL值。我想创建一个查询,即使它为NULL,也可以增加所有值。这是什么表

| Date      | Total Product Added | 
|---------- |-------------------- | 
| 18/07/01  |         100         |
| 18/05/01  |         300         |
| 18/01/01  |        1000         |

这是我期望的那张桌子

| Date      | Total Product Added |
|---------- |-------------------- |
| 18/07/01  |        1400         |
| 18/06/01  |        1300         |
| 18/05/01  |        1300         |
| 18/04/01  |        1000         |
| 18/03/01  |        1000         |
| 18/01/01  |        1000         |

我已经使用了此查询,但结果却不像我想要的那样:

select
    date,
    sum(total_product_added) over (order by date asc) as total_product,

from
    sold_product

group by
    date,
    total_product
order by
    date_created desc

当我使用该查询时,结果如下:

| Date      | Total Product Added |
|---------- |-------------------- |
| 18/07/01  |        1400         |
| 18/05/01  |        1300         |
| 18/01/01  |        1000         |

2 个答案:

答案 0 :(得分:1)

使用generate_series()

select gs.dte,
       sum(total_product_added) over (order by date asc) as total_product
from (select generate_series(min(sp.date), max(sp.date), interval '1 day') as dte
      from sold_product sp
     ) gs left join
     sold_product sp
     on sp.date = gs.dte
order by gs.dte;

答案 1 :(得分:0)

使用COALESCE:

select
    date,
    sum(COALESCE(total_product_added, 0)) over (order by date asc) as total_product,    
from
    sold_product    
group by
    date,
    total_product
order by
    date_created desc