查询以显示每月的所有项目

时间:2018-07-12 21:14:32

标签: sql sql-server database

我有两个表:已发货(项目,数量,日期,hpd)和预测(项目,数量,日期,预测),我需要以下内容

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

可能有这样的桌子吗? 非常感谢

2 个答案:

答案 0 :(得分:2)

嗯。这似乎很复杂。您似乎想在一个月内合并两个表中的行,而不丢失任何一个中的任何值。

如果是这样,我认为这可以满足您的要求:

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

答案 1 :(得分:1)

我建议您使用Calendar Table(临时表或简称为永久表)。

使用外部联接将日历表日期与每个发货日期和预测日期联接在一起。不要忘记将预测项目与发货项目一起加入。还可以处理来自发货和预测的数据是否为空

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