22,300
社区成员




WITH
/* 测试数据
table1(姓名,发售日期,票号起,票号止)AS(
SELECT '刘一','2015-03-01',101,110
)
,table2(姓名,缴回日期,票号起,票号止)AS(
SELECT '刘一','2015-06-02',101,103 UNION ALL
SELECT '刘一','2015-07-09',104,108
),*/
n AS (
SELECT number
FROM master..spt_values
WHERE type = 'p'
)
,a1 AS (
SELECT t.姓名,
t.发售日期,
t.票号起 + n.number 票号
FROM table1 t
JOIN n
ON n.number <= (t.票号止 - t.票号起)
)
,a2 AS (
SELECT t.姓名,
t.票号起 + n.number 票号
FROM table2 t
JOIN n
ON n.number <= (t.票号止 - t.票号起)
)
SELECT a1.*
FROM a1
LEFT JOIN a2
ON a1.票号 = a2.票号
WHERE a2.票号 IS NULL
姓名 发售日期 票号
---- ---------- -----------
刘一 2015-03-01 109
刘一 2015-03-01 110
create table a(name varchar(8), [date] datetime,[type] varchar(2),begin_id int,end_id int)
insert a select '劉一','2015.03.01','A',101,110
insert a select '陳二','2015.03.26','A',121,140
insert a select '張三','2015.05.04','A',141,150
insert a select '王四','2015.08.09','A',151,160
create table b(name varchar(8), [date] datetime,[type] varchar(2),begin_id int,end_id int)
insert b select '陳二','2015.05.04','A',121,124
insert b select '劉一','2015.06.02','A',101,103
insert b select '劉一','2015.07.09','A',104,108
insert b select '張三','2015.07.09','A',141,143
insert b select '王四','2015.09.09','A',151,155
insert b select '張三','2015.09.09','A',144,145
select * ,row_number()over(partition by name order by begin_id)as rn
into #t from
(select b.name,b.[type],b.begin_id,b.end_id
from b ,a
where DATEADD(MONTH,3,a.[date])>=b.[date]union all
select name,[type],null,begin_id-1 from a
union all
select name,[type],end_id+1,null from a)x
select m.name,m.[type], m.end_id+1 begin_id,n.begin_id-1 end_id
from #t m,#t n
where m.name=n.name
and n.begin_id>m.end_id+1
and n.rn=m.rn+1
/*
name type begin_id end_id
--------------------------------------------------------------
王四 A 156 160
張三 A 146 150
陳二 A 125 140
劉一 A 109 110
*/
drop table a,b,#t