日期:2014-05-16 浏览次数:20676 次
tab1
pid pname
1 层板
2 顶板
3 中侧板
tab2
id pid pcode
1 1 993029
2 1 993030
3 1 993031
4 2 311021
5 2 311022
6 3 223345
7 3 223346
8 3 223347
9 3 223348
MS SQL2000中,如何写一个SQL语句,执行后,查询结果如下:
pid pname allcode
1 层板 993029,993030,993031
2 顶板 311021,311022
3 中侧板 223345,223346,223347,223348
;with tab1(pid , pname) as
(
select 1,'层板'
union all select 2,'顶板'
union all select 3,'中侧板'
),
tab2(id , pid , pcode) as
(
select 1,1,'993029'
union all select 2,1,'993030'
union all select 3,1,'993031'
union all select 4,2,'311021'
union all select 5,2,'311022'
union all select 6,3,'223345'
union all select 7,3,'223346'
union all select 8,3,'223347'
union all select 9,3,'223348'
),cte as
(
select a.*,b.pname from tab2 a left join tab1 b on a.pid=b.pid
)
select a.pid,a.pname,
stuff((select ','+pcode from cte b
where b.pid=a.pid
for xml path('')),1,1,'') 'pcode'
from cte a
group by a.pid,a.pname
/*
pid pname pcode
1 层板 993029,993030,993031
2 顶板 311021,311022
3 中侧板 223345,223346,223347,223348
*/
create table tab1(pid int, pname varchar(100));
insert into tab1
select 1, '层板' union all
select 2, '顶板' union all
select 3, '中侧板'
create table tab2(id int, pid int, pcode varchar(100))
insert into tab2
select 1, 1, '993029' union all
select 2, 1, '993030' union all
select 3, 1, '993031' union all
select 4, 2, '311021' union all
select 5, 2, '311022' union all
select 6, 3, '223345' union all
select 7,&