好的,我知道 OP 已经被选择了一个解决方案。但是我用行生成器发布了我自己的解决方案。我认为这是一种优雅的方式来做到这一点。未来在这里:
拳头,创建表格并填充值:
create table #t (
Customer char(4), [Order] char(4), [Date] date, Amount money,
TransactionType varchar(50)
)
insert into #t values
( 'AABB','AB01','2012-06-01',3000,'Invoiced'),
( 'AABB','AB01','2012-06-05',3000,'Payment');
在这里,行生成器和它自己的查询:
declare @fromdate date
set @fromdate = '1/1/2001'
;WITH
Nbrs_3( n ) AS ( SELECT 1 UNION SELECT 0 ),
Nbrs_2( n ) AS ( SELECT 1 FROM Nbrs_3 n1 CROSS JOIN Nbrs_3 n2 ),
Nbrs_1( n ) AS ( SELECT 1 FROM Nbrs_2 n1 CROSS JOIN Nbrs_2 n2 ),
Nbrs_0( n ) AS ( SELECT 1 FROM Nbrs_1 n1 CROSS JOIN Nbrs_1 n2 ),
Nbrs ( n ) AS ( SELECT 1 FROM Nbrs_0 n1 CROSS JOIN Nbrs_0 n2 ),
all_dates as (
SELECT
dateadd( day, n , @fromDate) as [date]
FROM ( SELECT ROW_NUMBER() OVER (ORDER BY n)
FROM Nbrs ) D ( n )
),
all_intervals as (
select
t1.customer, t1.[order], t1.[date] as date_from, t1.amount as amount_due,
t2.[date] as date_paid
from
#t t1 inner join
#t t2 on t2.TransactionType = 'Payment'
and t1.customer = t2.customer and t1.[order] = t2.[order]
where t1.TransactionType = 'Invoiced'
)
select a.*, d.[date]
from all_intervals a
inner join all_dates d
on d.[date] between a.date_from and a.date_paid
结果:
customer order date_from amount_due date_paid date
-------- ----- ------------- ---------- ------------- -------------
AABB AB01 2012-06-01 00:00:003000 2012-06-05 00:00:002012-06-01 00:00:00
AABB AB01 2012-06-01 00:00:003000 2012-06-05 00:00:002012-06-02 00:00:00
AABB AB01 2012-06-01 00:00:003000 2012-06-05 00:00:002012-06-03 00:00:00
AABB AB01 2012-06-01 00:00:003000 2012-06-05 00:00:002012-06-04 00:00:00
AABB AB01 2012-06-01 00:00:003000 2012-06-05 00:00:002012-06-05 00:00:00
你可以试试。