日期:2014-05-17 浏览次数:20388 次
WITH A (ano,aname) AS
(
SELECT 'P01','上学' UNION ALL
SELECT 'P02','下课' UNION ALL
SELECT 'P03','上课' UNION ALL
SELECT 'P04','放学'
)
,B (bid, b1, b2, b3, b4) AS
(
SELECT 1,'P01','P04','P02','P03' UNION ALL
SELECT 2,'P02','P03','P04','P01'
)
SELECT bid
,(SELECT aname FROM A WHERE ano=B.b1) b1
,(SELECT aname FROM A WHERE ano=B.b2) b2
,(SELECT aname FROM A WHERE ano=B.b3) b3
,(SELECT aname FROM A WHERE ano=B.b4) b4
FROM B
--drop table A
--drop table B
create table A(ano varchar(20), aname varchar(20))
insert into A
select 'P01', '上学' union all
select 'P02', '下课' union all
select 'P03', '上课' union all
select 'P04', '放学'
create table B(
bid int,
b1 varchar(20),
b2 varchar(20),
b3 varchar(20),
b4 varchar(20)
)
insert into B
select 1 , 'P01', 'P04', 'P02', 'P03' union all
select 2 , 'P02', 'P03', 'P04', 'P01'
set statistics io on
--方法1,关联表
select b.bid,
a1.aname as b1,
a2.aname as b2,
a3.aname as b3,
a4.aname as b4
from B
left join A a1
on b.b1 = a1.ano
left join A a2
on b.b2 = a2.ano
left join A a3
on b.b3 = a3.ano
left join A a4
on b.b4 = a4.ano
/*
bid aname aname aname aname