sql—即使没有值,也用将来的日期填充行

zbdgwd5y  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(268)

故事:
我的数据集如下所示:

  1. +---------+------+-----------------+---------+
  2. | Date | Cost | Revenue Month | Revenue |
  3. +---------+------+-----------------+---------+
  4. | 2018-01 | 20 | 2018-02 | 20 |
  5. | 2018-01 | 20 | 2018-03 | 100 |
  6. | 2018-02 | 5 | 2018-03 | 15 |
  7. | 2018-02 | 5 | 2018-04 | 25 |
  8. +---------+------+-----------------+---------+

基本上,“日期”列表示初始投资,“收入月”表示因投资月而产生的资金。我希望在本月之前的每个后续月份都填写收入月份的行,并强制收入显示为0(即2020年8月)
目标:

  1. +---------+------+-----------------+---------+---------+
  2. | Date | Cost | Returning Month | Revenue | Product |
  3. +---------+------+-----------------+---------+---------+
  4. | 2018-01 | 20 | 2018-02 | 20 | A |
  5. | 2018-01 | 20 | 2018-03 | 100 | A |
  6. | 2018-01 | 20 | 2018-04 | 0 | A |
  7. | 2018-01 | 20 | 2018-05 | 0 | A |
  8. | 2018-02 | 5 | 2018-03 | 15 | A |
  9. | 2018-02 | 5 | 2018-04 | 25 | A |
  10. | 2018-02 | 5 | 2018-03 | 0 | A |
  11. | 2018-02 | 5 | 2018-03 | 0 | A |

我尝试的是:
我做了这个理货日期表

  1. DROP TABLE IF EXISTS ##dates
  2. CREATE TABLE ##dates ([date] Date)
  3. DECLARE @dIncr DATE = '01/01/2018'
  4. DECLARE @dEnd DATE = cast(getdate() as date)
  5. WHILE (@dIncr <= @dEnd)
  6. BEGIN
  7. INSERT INTO ##dates ([date]) VALUES (@dIncr)
  8. SELECT @dIncr = DATEADD(month,1,@dIncr)
  9. END

但我被这个困住了。

6psbrbz9

6psbrbz91#

如果你想增加两个月的数据,你可以使用 union all :

  1. select Date, Cost, Returning_Month, Revenue, Product
  2. from t
  3. union all
  4. select Date, Cost, dateadd(month, v.n, Returning_Month), 0 as Revenue, Product
  5. from (select date, cost, max(returning_month) as returning_month, revenue, product
  6. from t
  7. group by date, cost, revenue, product
  8. ) t cross apply
  9. (values (1), (2)) v(n);

编辑:
使用递归cte:

  1. with cte as (
  2. select date, cost, max(returning_month) as returning_month, revenue, product, 0 as lev
  3. from t
  4. group by date, cost, revenue, product
  5. union all
  6. select date, cost, dateadd(month, 1, returning_month), revenue, product, lev + 1
  7. from cte
  8. where returning_month < getdate()
  9. )
  10. select date, cost, returning_month, revenue, product
  11. from cte
  12. where lev > 0;
展开查看全部

相关问题