先说一下需求和场景
现有一个表数据:
A |
B | 1 |
A | C | 2 |
A | D | 3 |
A | E | 4 |
B | H | 5 |
H | Y | 6 |
Z | X | 7 |
Z | Y | 8 |
查询出来的数据,都要在前面有相同的内容,比如第八条数据显示出来是因为 第七条数据中有个"Y",第七条数据显示出来是因为第八条数据有个"Z",以此类推.就是这么的一种关系.
怎么用sql语句写出来呢?我擦问题来了!请看下面sql语句 ,如有函数不懂,请好好百度.
创建测试表
create TABLE testtable(
dual1 VARCHAR(10),
dual2 VARCHAR(10),
dual3 VARCHAR(10),
dual4 VARCHAR(10)
)
添加测试数据
INSERT into testtable VALUES('A','B','1','2');
INSERT into testtable VALUES('A','C','1','3');
INSERT into testtable VALUES('A','D','1','4');
INSERT into testtable VALUES('A','E','1','5');
INSERT into testtable VALUES('B','H','2','8');
INSERT into testtable VALUES('H','Y','8','25');
INSERT into testtable VALUES('Z','X','26','24');
INSERT into testtable VALUES('Z','Y','26','25');
编写查询语句
declare @B varchar(max),@BB varchar(max),
@D varchar(max),
@CC varchar(max),@sql varchar(max),
@t table([new] nvarchar(255))
select @B=coalesce(@B+',' , '')+d1.dual1 from (select dual1 from testtable) d1
select @D=coalesce(@D+',' , '')+d2.dual2 from (select dual2 from testtable) d2
Set @CC=@B+','+@D
set @sql='select col='''+ replace(@CC,',',''' union all select ''')+''''
insert into @t exec(@sql)
select @BB=coalesce(@BB+',','')+newt.new from (select new,count(*) as num from @t group by new) newt where newt.num>1
select * from testtable where (@BB like '%'+dual1+'%' or @BB like '%'+dual2+'%' )
完毕!!!!!!!!