create table a(id int,name nvarchar(1))
insert a values(1,N'A')
insert a values(2,N'B')
insert a values(3,N'C')
create table b(id int,id1 int ,id2 int)
insert b values(1,2,3)
现在,想把b表中的1,2,3换成A表对应的name显示出来,最简单的SQL语句怎么写?
PS:SqlServer2008
create table #a(id int,name nvarchar(1)) insert #a values(1,N'A') insert #a values(2,N'B') insert #a values(3,N'C') create table #b(id int,id1 int ,id2 int) insert #b values(1,2,3) SELECT a.name,a1.name ,a2.name FROM #b b INNER JOIN #a a ON a.id = b.id INNER JOIN #a a1 ON a1.id = b.id1 INNER JOIN #a a2 ON a2.id = b.id2 DROP TABLE #a DROP TABLE #b
create table #a(id int,name nvarchar(1)) insert #a values(1,N'A') insert #a values(2,N'B') insert #a values(3,N'C') create table #b(id int,id1 int ,id2 int) insert #b values(1,2,3) select * from ( select * from #b unpivot(value for ids in (id,id1,id2)) as vpt ) as a inner join #a b on a.value=b.id
行转列pivot和unpiovt真是个利器,顶你
改成这样就完美了
select ids,name from ( select * from b unpivot(value for ids in (id,id1,id2)) as vpt ) as a inner join a b on a.value=b.id
@心态要好:
行专列出来的结果是
id A
id1 B
id2 C
你说的 “b表中的1,2,3换成A表对应的name显示出来” 理解成了
结果 A B C
回答问题理解有误差了,囧。。。。。。
仅供参考 我这sql挺没水平的,等高人吧,楼主还是放些分比容容易吸引高手
select id=(select name from a where a.id=b.id) ,id1=(select name from a where a.id=b.id1) ,id2=(select name from a where a.id=b.id2) from b
mark
现实场景到底是怎么样的呢?如果列不多,直接多个表连接吧
select _a.name from a as _a inner join b as _b on _b.id = _a.id
试试我这个,效率高,而且简单:
1 SELECT (SELECT C_NAME FROM T_A WHERE ID = B.ID) N1, 2 (SELECT C_NAME FROM A WHERE ID = B.C_ID1) N2, 3 (SELECT C_NAME FROM A WHERE ID = B.C_ID2) N3 4 FROM B
欢迎讨论!