日期:2014-05-17  浏览次数:20554 次

求个SQL语句,十分感谢!
我现在系统中需要用到一个SQL语句,没有办法使用存储过程,只能用SQL实现,想得到如下效果:
如果table1中有如下Col1,Col2两列,table2中有Col1,Col3两列。数据如下:
table1:
Col1   Col2
0001   3
0002   4
0002   5

table2:
Col1    Col3
0002    6

直接用leftjoin话得到的结果如下:
Col1   Col2    Col3
0001   3       
0002   4       6
0002   5       6

但是我想实现这种效果:
Col1   Col2    Col3
0001   3       
0002   4       6
0002   5       
就是左连接如果Col1数据重复,只是连接到第一列,重复的就变成空。
这样的sql该如何写啊?求助。

------解决方案--------------------
create table table1(Col1 varchar(10),  Col2 int)

insert into table1
select '0001',   3 union all
select '0002',   4 union all
select '0002',   5

create table table2(Col1 varchar(10),   Col3 int)

insert into table2
select '0002',    6
go

select t1.Col1,t1.Col2,
       case when row_number() over(PARTITION by t1.col1 
                                       order by @@servername)=1
                 then t2.Col3
            else null
       end as col3
from table1 t1
left join table2 t2
       on t1.Col1 = t2.Col1
/*
Col1 Col2 col3
0001 3 NULL
0002 4 6
0002 5 NULL
*/

------解决方案--------------------
table1 左连接 select a.*,b.Col2 from table2 a ,(select Col1 , min(Col2) as Col2  from table2 group by Col1  ) where a.Col1    =b.Col1