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

标签 sql sql-server database

我有两个表:已发货(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/

相关文章:

php - 缺少数据库表 - CakePHP

SQL数据库结构

mysql - 如何在mysql中获取下一个自动增量ID

sql-server - 递归顺序 (SQL Server CTE)

java - JDBC 在 "same"时间打开 2 个连接

新手的Mysql存储过程方程一步一步?

mysql - 重新格式化表数据sql

javascript - 如何将一个值推到值组合框中的最后一个值

MYSQL查询从状态表中获取多个状态

c# - 将 ORACLE SDO_GEOMETRY 导入 SQL Server 几何