【问题标题】:How to insert missing years in temporary table in MS SQL Server如何在 MS SQL Server 的临时表中插入缺失的年份
【发布时间】:2022-12-03 03:55:43
【问题描述】:

我在销售部门工作,问题是这张表没有每年每个客户的记录。记录随机丢失。相反,我需要将那些年放在那里,并将那些年的销售额设为 0 以供我分析。

我对 SQL 的了解有限。有人可以帮忙吗?我现在拥有的和我想要的如下所示。

我想使用 LAG() 函数,但丢失的记录可能连续 2 年或 3 年。我不确定如何解决此类问题。

我现在拥有的:

Client_ID SalesYear Sales
1 2010 12
1 2012 20
1 2013 21
1 2016 14

我需要的是:

Client_ID SalesYear Sales
1 2010 12
1 2011 0
1 2012 20
1 2013 21
1 2014 0
1 2015 0
1 2016 14

【问题讨论】:

    标签: sql-server


    【解决方案1】:

    您需要一个完整的年份列表才能进行外部连接。

    你可以通过多种方式做到这一点,基本原则是:

    with y as (
      select * from (values(2010),(2011),(2012),(2013),(2014),(2015),(2016))y(y)
    )
    insert into t (Client_Id, SalesYear, Sales)
    select 1, y.y, 0
    from y
    where not exists (select * from t where t.SalesYear = y.y);
    

    【讨论】:

      【解决方案2】:

      这样的事情可能会有所帮助:

      DECLARE @Sales TABLE
      (Client_ID int, SalesYear int, Sales money)
      
      INSERT INTO @Sales(Client_ID, SalesYear, Sales) SELECT 1, 2010, 12 
      INSERT INTO @Sales(Client_ID, SalesYear, Sales) SELECT 1, 2012, 20 
      INSERT INTO @Sales(Client_ID, SalesYear, Sales) SELECT 1, 2013, 21 
      INSERT INTO @Sales(Client_ID, SalesYear, Sales) SELECT 1, 2016, 14;
      
      
      
      with years as 
      (
          select 1900 as theYear 
          UNION ALL
          select y.theYear + 1 as theYear
          from years y
          where y.theYear + 1 <= YEAR(GetDate())
      )
      
      select 
          Y.theYear, S.Client_ID, S.Sales
      FROM 
          Years Y
      LEFT JOIN
          @Sales S ON S.SalesYear = Y.theYear
      option (maxrecursion 0)
      

      您可以将“1900”更改为更合适的内容。

      【讨论】:

        猜你喜欢
        • 2023-02-06
        • 1970-01-01
        • 2021-11-20
        • 2011-02-05
        • 1970-01-01
        • 2014-01-24
        • 2011-08-21
        • 2018-09-01
        • 1970-01-01
        相关资源
        最近更新 更多