读书人

sql语句多谢各位

发布时间: 2012-01-19 20:57:58 作者: rapoo

求一个sql语句,谢谢各位
t1
a b
1 11
2 11
3 34

t2
c d
1 0
1 1
1 2
2 0
2 1

要输出的结果!
a b c d
1 11 1 2
2 11 2 1
3 34 null null

[解决办法]
declare @t1 table (a int,b int)
declare @t2 table (c int,d int)
insert into @t1
select 1,11
union all
select 2,11
union all
select 3,34
insert into @t2
select 1,0
union all
select 1,1
union all
select 1,2
union all
select 2,0
union all
select 2,1
select * from @t1
select * from @t2
--query result
select * from @t1 a left join
(select c,max(d) as d from @t2 group by c) d
on a.a=d.c

读书人网 >SQL Server

热点推荐