我有两个表:已发货(item、qty_shipd、date_shpd)和预测(item、qty_forecat、date_forecast),我需要以下内容
Item Forecast Shipped Forecast_date Shipped_date
item1 50 100 2018-01-01 2018-01-15
item2 0 50 - 2018-01-06
item3 100 100 2018-02-01 2018-02-05
item4 150 0 2018-02-01 -
item1 0 20 - 2018-03-15
item1 10 50 2018-04-01 2018-04-28
是否可能有类似这张表的东西? 非常感谢
最佳答案
嗯。这看起来相当复杂。您似乎希望在一个月内合并两个表中的行,而不丢失任何一个表中的任何值。
如果是这样,我认为这符合您的要求:
select item, max(shipped) as shipped, max(shipped_date) as shipped_date,
max(forecast) as forecast, max(forecast_date) as forecast_date
from ((select Item, Shipped, Shipped_date, null as forecast, null as forecast_date,
row_number() over (partition by item, year(shipped_date), month(shipped_date) order by shipped_date) as seqnum
from shipped
) union all
(select Item, NULL as Shipped, NULL as Shipped_date, null as forecast, null as forecast_date,
row_number() over (partition by item, year(shipped_date), month(shipped_date) order by shipped_date) as seqnum
from shipped
)
) sf
group by item, year(coalesce(shipped_date, forecast_date)),
month(coalesce(shipped_date, forecast_date)), seqnum
关于sql - 查询以显示每个月的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51314552/