【问题标题】:SQL Server 2008 Inserting new record for missing dates in a tableSQL Server 2008 在表中插入缺少日期的新记录
【发布时间】:2014-12-17 22:33:48
【问题描述】:

我有两个 sql 表 表 1 列:产品、结束日期(例如:2014-01-31 00:00:00.000)、saleAmt Table2 只有一列:EndDate (eg: 2014-01-31 00:00:00.000)

第一个表包含过去 12 个月内每个产品的 TotalMonthly 销售额。 问题:某些产品在一个月内没有任何销售额,因此不会显示该产品当月的数据。我希望以 0 的销售额显示缺失的月份

现在 Table1 中的数据是这样的:

**Product   EndDate   SaleAmt**
TireMC  12/31/2013     5600
TireMC  1/31/2014      800
TireMC  2/28/2014      2400
TireMC  7/31/2014      1600
TireMC  10/31/2014     4600
TireMC  11/30/2014     4200

我想将此 table1 日期与 Table2 日期进行比较,并将 Table1 中每个产品的缺失日期从 Table2 获取到 Table1 中,并将这些的 SalesAmt 保留为空。

**Product   EndDate        SaleAmt**
TireMC  12/31/2013         5600
TireMC  1/31/2014            800
TireMC  2/28/2014            2400
TireMC  3/31/2014            0
TireMC  4/30/2014            0
TireMC  5/31/2014            0
TireMC  6/30/2014            0
TireMC  7/31/2014            1600
TireMC  8/31/2014            0
TireMC  9/30/2014            0
TireMC  10/31/2014           4600
TireMC  11/30/2014           4200

我怎样才能做到这一点。

提前感谢您的帮助。

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    如果我正确理解您的问题,您正在查找第二个表中所有日期的 cartesian product,以及第一个表中的所有产品。您可以使用cross join 来创建它。然后你需要使用outer join 来获取相同amt 的结果,使用coalesce 将空值转换为0:

    select t1.product, t2.enddate, coalesce(t3.saleamt,0) saleamt
    from (select distinct product
          from table1) t1
    cross join (select distinct enddate
                from table2) t2
    left join table1 t3 on t1.product = t3.product 
      and t2.enddate = t3.enddate
    

    【讨论】:

    • 这个选择给了我想要的结果,但是如何将每个产品缺少的日期记录放回 Table1 中?
    • @svon - 只需使用 insert into ... select ... 并添加一个空检查 - 应该这样做:sqlfiddle.com/#!3/64202/1
    猜你喜欢
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 2011-05-09
    相关资源
    最近更新 更多