首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求两张表查询的SQL语句,该如何处理

2012-03-23 
求两张表查询的SQL语句两张表T1,T2T1中2个字段为 ComId,heightT2中2个字段为 ComId,widthT1中数据如下ComI

求两张表查询的SQL语句
两张表T1,T2
T1中2个字段为 ComId,height
T2中2个字段为 ComId,width

T1中数据如下
ComId height
A1 oo
A1 hh

T2中数据如下
ComId width
A1 T2
A1 T3
A1 T4

希望得到如下查询结果
ComId Height Width
A1 00 T2
  hh T3
  T4

希望高人出招。

[解决办法]

SQL code
use testgocreate  table #t1(ComId char(2),height char(2))insert #t1 select 'A1','oo' insert #t1 select 'A1','hh' gocreate  table #t2(ComId char(2),width char(2)) insert #t2 select 'A1','T2' insert #t2 select 'A1','T3' insert #t2 select 'A1','T4'goselect *,row=1 into #a from #t1 order by ComIdselect *,row=1 into #b from #t2 order by ComIdgodeclare @ComId char(2),@i intupdate #aset @i=case when ComId=@ComId then @i+1 else 1 end,row=@i,@ComId=ComIdset @i=0update #bset @i=case when ComId=@ComId then @i+1 else 1 end,row=@i,@ComId=ComIdgoselect    [ComId]=case when a.row=(select min(row) from #b where ComId=b.ComId) then b.ComId else ''end,    [height]=isnull(a.height,''),    b.widthfrom     #b b left join    #a a on b.ComId=a.ComId and b.row=a.row/*ComId height width ----- ------ ----- A1    oo     T2      hh     T3             T4(所影响的行数为 3 行)*/ 

热点排行