日期:2014-05-18  浏览次数:20560 次

跪求SQL2005查询语句!!!
求SQL2005查询语句
表t
id 姓名 年龄
01 李白 20
02 杜甫 21
03 张飞 22
04 宋江 24
05 岳飞 25
匹配情况如下(不唯一)

id 姓名 年龄 id2 姓名2 年龄2
01 李白 20 02 杜甫 21
02 杜甫 21 03 张飞 22 
03 张飞 22 04 宋江 23
04 宋江 23 05 岳飞
05 岳飞 24  
条件:
1、将年龄差值=1岁的进行匹配;
2、一列中id(id2)不能出现重复值;
比如可以和杜甫匹配的有李白、张飞,只能任选一人匹配,且已匹配过的,比如李白和张飞任一人和杜甫匹配过,就不能再和其他人匹配。
3、使匹配数量达到最大化。即ID2最多;

如下为错误:
id 姓名 年龄 id2 姓名2 年龄2
01 李白 20 02 杜甫 21
02 杜甫 21 01 李白 20
02 杜甫 21 03 张飞 22 
03 宋江 23 03 张飞 22
。。。
因为在ID和id2中均出现重复值。

------解决方案--------------------
如果改宋江的年龄:
SQL code
create table tb(id varchar(10),姓名 nvarchar(10),年龄 int)
insert into tb select '01','李白',20
insert into tb select '02','杜甫',21
insert into tb select '03','张飞',22
insert into tb select '04','宋江',23  --假如这里改成23
insert into tb select '05','岳飞',25
go
;with cte as(
select 1 as rn,id as id1,* from tb a where exists(select 1 from tb where 年龄=a.年龄+1)
and not exists(select 1 from tb where 年龄=a.年龄-1)
union all
select a.rn+1,a.id1,b.* from cte a inner join tb b on a.年龄=b.年龄-1
)select a.id,a.姓名,a.年龄,b.id as id2,b.姓名 as 姓名2,b.年龄 as 年龄2 
from cte a inner join cte b on a.id1=b.id1 and a.rn=b.rn-1
where exists(select 1 from cte where id1=a.id1 and rn=(select max(rn) from cte))
/*
id         姓名         年龄          id2        姓名2        年龄2
---------- ---------- ----------- ---------- ---------- -----------
01         李白         20          02         杜甫         21
02         杜甫         21          03         张飞         22
03         张飞         22          04         宋江         23

(3 行受影响)

*/
go
drop table tb

------解决方案--------------------
探讨
如果改宋江的年龄:

SQL code
create table tb(id varchar(10),姓名 nvarchar(10),年龄 int)
insert into tb select '01','李白',20
insert into tb select '02','杜甫',21
insert into tb select '03','张飞',22
insert into t……

------解决方案--------------------
看着这些高手我们这些菜鸟还怎么混哪