SQL在现有记录之间插入行

时间:2017-01-30 16:16:41

标签: sql

我有一张表,其记录仅对应于贷款的具体日期和贷款 - 即每笔贷款两笔记录。

Loans

Loan ID | Month     | Rate  | Action
--------------------------------
1       | 5/1/2000  | 5.50% | New
1       | 9/1/2000  | 6.00% | Closed
2       | 3/1/2000  | 5.25% | New
2       | 5/2/2000  | 5.50% | Closed

我还有另一个关于每个日期利率的记录。

Interest rates

Month       | Rate
--------------------
1/1/2000    | 5.00%
2/1/2000    | 5.25%
3/1/2000    | 5.25%
4/1/2000    | 5.25%
5/1/2000    | 5.50%
6/1/2000    | 5.50%
7/1/2000    | 5.50%
8/1/2000    | 6.00%
9/1/2000    | 6.00%
10/1/2000   | 6.50%

我想在取出和偿还给定贷款之间插入贷款表中缺少日期的行(以及相应的利率)。鉴于需要为每笔贷款插入中间日期,我无法通过LEFT JOIN,MERGE等解决这个问题。

预期结果:

Loan ID | Month     | Rate  | Action
---------------------------------
1       | 5/1/2000  | 5.50% | New
1       | 6/1/2000  | 5.50% | NULL
1       | 7/1/2000  | 5.50% | NULL
1       | 8/1/2000  | 6%    | NULL
1       | 9/1/2000  | 6%    | Closed
2       | 3/1/2000  | 5.25% | New
2       | 4/1/2000  | 5.25% | NULL
2       | 5/1/2000  | 5.50% | Closed

2 个答案:

答案 0 :(得分:0)

你的设计很难做到,你没有说出你正在使用的数据库。这是SQL服务器的示例(查询也适用于postgreSQL):

<a href="firebug-2.0.18-fx.xpi"
hash="sha1:C7AF7F925C611EC88979FD905943584A2A891420"
onclick="return install(event);">Install Extension!</a>

答案 1 :(得分:0)

当您需要为一系列日期生成行时,Numbers表通常很有用。它只是一个包含大量整数的表。您可以阅读有关如何创建一个here(以及其他地方)的信息。完成后,您可以使用这样的查询(这适用于SQL Server):

;with cteLoan as(
select t1.LoanID, min(t1.Month) StartDate, max(t1.Month) EndDate
from Table1 t1
group by t1.LoanID
)

select c.LoanID, dateadd(month, n.Number, c.StartDate) Month, t2.Rate, null Action
from Numbers n
cross join cteLoan c
join Table2 t2 on t2.Month = dateadd(month, n.Number, c.StartDate)
where n.Number >= 0 and n.number < DATEDIFF(month, c.StartDate, c.EndDate) 

union

select t1.LoanID, t1.Month, t1.Rate, t1.Action
from Table1 t1
order by LoanID, Month

要将结果插入另一个表,您应该能够:

insert into Results(LoadID, Month, Rate, Action)
select c.LoanID, dateadd(month, n.Number, c.StartDate) Month, t2.Rate, null Action
from Numbers n
cross join cteLoan c
join Table2 t2 on t2.Month = dateadd(month, n.Number, c.StartDate)
where n.Number >= 0 and n.number < DATEDIFF(month, c.StartDate, c.EndDate) 

union

select t1.LoanID, t1.Month, t1.Rate, t1.Action
from Table1 t1
order by LoanID, Month