# 两个表，找出第二个表中未及时缴回的票号

xbkm1201 2015-09-16 05:17:03

...全文
95 3 打赏 收藏 举报

3 条回复

Tiger_Zhao 2015-09-17
``````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``````

``````姓名 发售日期          票号
---- ---------- -----------

• 打赏
• 举报

hhhttt_ 2015-09-17
``````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
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
--------------------------------------------------------------

*/
drop table a,b,#t
``````
• 打赏
• 举报

xbkm1201 2015-09-16
• 打赏
• 举报

2.1w+

MS-SQL Server 疑难问题

2015-09-16 05:17