兩表串連,如果串連的表中有兩條以上匹配的記錄,只選出第一條

來源:互聯網
上載者:User

 

A表
empid  name 
A01    tom
A02    mary
A03    gary

B表
ClassID  empid  cname
C01       A01    english
C02       A01    math
C03       A02    physics

想要結果:
empid  classid  name  cname
A01     C01     tom   english
A02     C03     mary  physics
A03     NULL  gary    NULL

 

正解一: 

declare @t1 table(empid varchar(10),name varchar(10))
insert @t1 select 'A01'  ,  'tom' 
insert @t1 select 'A02'  ,  'mary' 
insert @t1 select 'A03'  ,  'gary'

declare @t2 table(classid varchar(10),empid varchar(10),cname varchar(10))
insert @t2 select 'C01'   ,    'A01'  ,  'english' 
insert @t2 select 'C02'   ,    'A01'  ,  'math' 
insert @t2 select 'C03'   ,    'A02'  ,  'physics'

select 
a.empid,b1.classid,a.name,b1.cname 
from @t1 a
left join @t2 b1
on a.empid=b1.empid and not exists (select 1 from @t2 where empid=b1.empid and classid<b1.classid)

--結果
empid      classid    name       cname      
---------- ---------- ---------- ---------- 
A01        C01        tom        english
A02        C03        mary       physics
A03        NULL       gary       NULL

(所影響的行數為 3 行)

 正確二: 

declare @t1 table(empid varchar(10),name varchar(10))
insert @t1 select 'A01'  ,  'tom' 
insert @t1 select 'A02'  ,  'mary' 
insert @t1 select 'A03'  ,  'gary'

declare @t2 table(classid varchar(10),empid varchar(10),cname varchar(10))
insert @t2 select 'C01'   ,    'A01'  ,  'english' 
insert @t2 select 'C02'   ,    'A01'  ,  'math' 
insert @t2 select 'C03'   ,    'A02'  ,  'physics'
--select 1 from @t2 tmp where empid=tmp.empid and classid<tmp.classid
--select * from @t2 tmp where not exists (select 1 from @t2 where empid=tmp.empid and classid<tmp.classid)

select t1.empid,t2.classid,t1.name,t2.cname
from @t1 t1
left join (select * from @t2 tmp where not exists (select 1 from @t2 where empid=tmp.empid and classid<tmp.classid)) t2
on t1.empid=t2.empid

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.