sql server2005: 如何通过语句 将某表里数据显示成另外表的字段...
问题是这样,表1(id,field1),表2(field2)--表2是保存自定义字段及值,表3(id,field3,value)其中id是对应表1中id,若想将表3中field3 值添加做为表1的字段,并将值value显示;
例如:
表1:select id,field1 from 表1
结果:
1,111
2,222
...
表2:select field2 from 表2
结果:
code
name
表3:select id,field3,value from 表3
结果:
1,code,aaaa
1,name,bbbb
2,code,ab
2,name,aabb
...
最终想得到:select id,field1,code,name from 表1
结果:
1,111,aaaa,bbbb
2,222,ab,aabb
...
请问有什么语句可以实现,谢谢!
[解决办法]
create table t1(id int,c1 varchar(100))goinsert t1select 1,'111' unionselect 2,'222'create table t2(c2 varchar(100))go insert t2select 'code' unionselect 'name'create table t3(id int,c3 varchar(100), val varchar(100))go insert t3select 1,'code','aaaa' unionselect 1,'name','bbbb' unionselect 2,'code','ab' unionselect 2,'name','aabb'goselect a.ID,col = c1+(select ','+val from t3 where ID = a.id for XML path('')) from t3 a join t1 b on a.id = b.idgroup by a.id,b.c1 order by a.idgodrop table t1,t2,t3
[解决办法]
create table 表1(id int, field1 varchar(6))insert into 表1select 1,'111' union allselect 2,'222'create table 表2(field2 varchar(6))insert into 表2select 'code' union allselect 'name'create table 表3(id int, field3 varchar(6), value varchar(6))insert into 表3select 1, 'code', 'aaaa' union allselect 1, 'name', 'bbbb' union allselect 2, 'code', 'ab' union allselect 2, 'name', 'aabb'select a.id,a.field1,c.code,c.namefrom 表1 ainner join(select id,code,namefrom 表3 tpivot(max(value) for field3 in(code,name)) v) con a.id=c.id id field1 code name----------- ------ ------ ------1 111 aaaa bbbb2 222 ab aabb(2 row(s) affected)