SQL根据日期范围插入多行

时间:2015-03-07 19:32:10

标签: sql-server date

我需要根据日期范围为多个插入编写sql。例如,我的成员12的开始日期为2014年1月1日至2014年12月31日。我需要每月插入一行(其中12个)到表中。我需要将此信息与已经以这种方式扩展的表进行比较。任何帮助,将不胜感激。 示例输入

client    amount       start           end         numpymtmths

12      $3000      01/01/2014     03/31/2014     03

13      $700       06/01/2014     12/31/2014     07

需要将其展开为:

client  amount     paydate     
12      $1000      201401    
12      $1000      201402  
12      $1000      201403    
13      $100       201406  
13      $100       201407    
13      $100       201408  
13      $100       201409  
13      $100       201410  
13      $100       201411  
13      $100       201412 

1 个答案:

答案 0 :(得分:0)

要分割数据,您需要拥有一个数字表(或数月)或动态创建它,例如使用CTE。 CTE解决方案看起来像这样:

with n1(n) as (
  select 1 union all select 1 union all 
  select 1 union all select 1 union all 
  select 1 union all select 1 union all 
  select 1 union all select 1 union all 
  select 1 union all select 1
),
n(n) as (
  select row_number() over (order by (select null)) - 1 
  from n1 cross join n1 as n2
)

select client, amount / numpymtmths, dateadd(month, n.n, start) as month 
from payment
join n on n.n < numpymtmths
order by client, month

现在限制为100个月(在CTE中加入10 x 10个数字)。

SQL小提琴:http://sqlfiddle.com/#!6/dee75/2

相关问题