Sql 查询以显示每个月的所有项目
我有两个表格:发货(项目,发货数量,发货日期)和预测(项目,发货数量,发货日期),我需要下面的东西Sql 查询以显示每个月的所有项目,sql,sql-server,database,Sql,Sql Server,Database,我有两个表格:发货(项目,发货数量,发货日期)和预测(项目,发货数量,发货日期),我需要下面的东西 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-
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
我建议您使用(临时或简单的永久表)
使用外部联接将日历表日期与每个发货日期和预测日期联接。不要忘记将forecast item与shipped item连接起来。如果来自shipped和forecast的数据为空,也要进行处理
SELECT
ISNULL(f.item, s.item) AS Item,
c.Date,
ISNULL(qty_forecat,0) AS Forecast,
ISNULL(qty_shipd,0) AS Shipped,
date_forecast AS Forecast_date,
date_shpd AS Shipped_date
FROM
Calendar AS c
LEFT OUTER JOIN forecast AS f
ON c.Date=f.date_forecast
LEFT OUTER JOIN shipped AS s
ON c.Date=s.date_shpd
AND f.item=s.item
您需要显示原始数据。目前还不清楚这些是如何结合起来的。