Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 用未来日期填充行,即使没有值_Sql_Sql Server - Fatal编程技术网

Sql 用未来日期填充行,即使没有值

Sql 用未来日期填充行,即使没有值,sql,sql-server,Sql,Sql Server,故事: 我的数据集如下所示: +---------+------+-----------------+---------+ | Date | Cost | Revenue Month | Revenue | +---------+------+-----------------+---------+ | 2018-01 | 20 | 2018-02 | 20 | | 2018-01 | 20 | 2018-03 | 100 |

故事:

我的数据集如下所示:

+---------+------+-----------------+---------+
|  Date   | Cost | Revenue   Month | Revenue |
+---------+------+-----------------+---------+
| 2018-01 |   20 | 2018-02         |      20 |
| 2018-01 |   20 | 2018-03         |     100 |
| 2018-02 |    5 | 2018-03         |      15 |
| 2018-02 |    5 | 2018-04         |      25 |
+---------+------+-----------------+---------+
基本上,日期列表示初始投资,收入月表示由于投资月而产生的资金。我希望在本月之前的每个后续月份填写收入月的行,并强制收入显示为0,即2020年8月

目标:

我尝试的是:

我建立了这个理货日期表

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

但我一直坚持这一点。

如果您想在数据中添加两个月,您可以使用union all:

编辑:

使用递归CTE:

with cte as (
      select date, cost, max(returning_month) as returning_month, revenue, product, 0 as lev
      from t
      group by date, cost, revenue, product
      union all
      select date, cost, dateadd(month, 1, returning_month), revenue, product, lev + 1
      from cte
      where returning_month < getdate()
     )
select date, cost, returning_month, revenue, product
from cte
where lev > 0;

不只是两个月,而是直到本月的所有后续月份
select  Date, Cost, Returning_Month, Revenue, Product 
from t
union all
select  Date, Cost, dateadd(month, v.n, Returning_Month), 0 as Revenue, Product 
from (select date, cost, max(returning_month) as returning_month, revenue, product
      from t
      group by date, cost, revenue, product
     ) t cross apply
     (values (1), (2)) v(n);
with cte as (
      select date, cost, max(returning_month) as returning_month, revenue, product, 0 as lev
      from t
      group by date, cost, revenue, product
      union all
      select date, cost, dateadd(month, 1, returning_month), revenue, product, lev + 1
      from cte
      where returning_month < getdate()
     )
select date, cost, returning_month, revenue, product
from cte
where lev > 0;