表 table1
codea codeb
8 2
3 1
5 3
2 7
表 table2
code name
1 tom
2 kate
3 sherry
........
........
........
codea 和 codeb 分别都是学号,我要生成一个表 ,类似以下格式,请问sql 怎么写,要求简洁而且效率高的写法。
codea codeb nameA nameB
3 2 sherry kate
3 1
5 3
2 7
codea codeb
8 2
3 1
5 3
2 7
表 table2
code name
1 tom
2 kate
3 sherry
........
........
........
codea 和 codeb 分别都是学号,我要生成一个表 ,类似以下格式,请问sql 怎么写,要求简洁而且效率高的写法。
codea codeb nameA nameB
3 2 sherry kate
3 1
5 3
2 7
解决方案 »
- 急急急急急急急急急急急急急急急急!!!!!查询问题
- 怎么把textbox的值更新到数据表对应id列值中
- ???sql server如何加锁?
- 求助我这个表的行大小怎么会有8062??
- SQL 某数字和字母自助组合,且无重复数字的语法
- 一个应用实例的疑惑
- SQL Server 复制发布-采用事务日志,报当 IDENTITY_INSERT 设置为 OFF 时,不能为表 'Links' 中的标识列插入显式值。
- 我有一个表,有30个字段,我想提取所有字段,但有2两个字段除外,我不想把这30个字段一一列出,有没简单的办法.
- SQL经典问题
- =急=急=急=这个SQL语句是什么意思??
- sql查询问题
- 求教 急知道
select A.codea,A.codeb,B.name as nameA,C.name as nameB
from table1 as A
left join table2 as B on A.codea=B.code
left join table2 as C on A.codeb=C.code
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
create table [table1]([codea] int,[codeb] int)
insert [table1]
select 8,2 union all
select 3,1 union all
select 5,3 union all
select 2,7
--> 测试数据:[table2]
if object_id('[table2]') is not null drop table [table2]
create table [table2]([code] int,[name] varchar(6))
insert [table2]
select 1,'tom' union all
select 2,'kate' union all
select 3,'sherry' union all
select 4,'tracy'select
a.*,isnull(b.name,'') as nameA,
isnull(c.name,'') as nameB
from table1 a
left join table2 b on a.codea=b.code
left join table2 c on a.codeb=c.code
/*
codea codeb nameA nameB
---------------------------------------------
8 2 kate
3 1 sherry tom
5 3 sherry
2 7 kate
*/
(select #t2.name from #t2 where #t2.code=#t1.codea) nameb from #t1;