pno iqcchkno childpno
00-002-332-AA Q101200018 YL-WJL-001-OA
00-002-332-AA Q110100001 YL-WJL-001-OA
00-002-332-AA Q110100002 YL-WJL-001-OA
00-002-332-AA Q110100007 YL-SJL-004-AA
00-002-332-AA Q101200029 BC-ZXL-004-CA
NULL 00-002-332-AA
要求显示如下:
00-002-332-aa
yl-wjl-001-0a
Q101200018
Q110100001
Q110100002
yl-sjl-004-aa
Q110100007
bc-zxl-004-ca
Q101200029
union all
select pno,iqcchkno as AA from tb
order by pno
1楼的测试结果如下:
00-002-332-AA
NULL
00-002-332-AA BC-ZXL-004-CA
00-002-332-AA YL-SJL-004-AA
00-002-332-AA YL-WJL-001-OA
00-002-332-AA Q101200018
00-002-332-AA Q110100001
00-002-332-AA Q110100002
00-002-332-AA Q110100007
00-002-332-AA Q101200029
select pno,AA from (
select distinct pno,childpno as AA, childpno from tb
union all
select pno,iqcchkno as AA,childpno from tb) a
order by pno,childpno,AA
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([pno] varchar(13),[iqcchkno] varchar(10),[childpno] varchar(13))
insert [tb]
select '00-002-332-AA','Q101200018','YL-WJL-001-OA' union all
select '00-002-332-AA','Q110100001','YL-WJL-001-OA' union all
select '00-002-332-AA','Q110100002','YL-WJL-001-OA' union all
select '00-002-332-AA','Q110100007','YL-SJL-004-AA' union all
select '00-002-332-AA','Q101200029','BC-ZXL-004-CA' union all
select null,null,'00-002-332-AA'
---查询---
select result
from(
select childpno as pno,'' as childpno,childpno as result from tb where iqcchkno is null
union all
select distinct pno,childpno,' '+childpno from tb where iqcchkno is not null
union all
select pno,childpno,' '+iqcchkno from tb where iqcchkno is not null
) t
order by pno,childpno,result desc
---结果---
result
------------------
00-002-332-AA
BC-ZXL-004-CA
Q101200029
YL-SJL-004-AA
Q110100007
YL-WJL-001-OA
Q110100002
Q110100001
Q101200018(9 行受影响)