拓狼 - 1/6/2010 2:44:00 AM
要求:对于col1相同的值,如果col2里存在值为2的记录,就取col2=2的最大id的那条记录,如果不存在值为2的,就取col2=1的最大id的那条记录。
要求:
1、使用基于集合的方式进行处理
2、不能使用表变量、临时表、while循环、自定义函数
3、可以使用CTE
用下列代码生成测试数据:
declare @t table
(
id int identity,
col1 int,
col2 int
)
insert into @t
select 1,1
union all select 1,2
union all select 1,1
union all select 2,1
union all select 2,1
union all select 2,1
union all select 2,1
union all select 3,1
union all select 3,2
union all select 3,1
union all select 3,2
select * from @t
生成的示例数据如下:
id col1 col2
----------- ----------- -----------
1 1 1
2 1 2
3 1 1
4 2 1
5 2 1
6 2 1
7 2 1
8 3 1
9 3 2
10 3 1
11 3 2
生成下面的结果:
id col1 col2
----------- ----------- -----------
2 1 2
7 2 1
11 3 2
zsforever - 1/6/2010 7:41:00 PM
select *
from @t a
where id=(select top 1 id from @t where col1=a.col1
order by col2 desc,id desc)
tieqilin - 5/4/2010 2:53:00 AM
不错,学到一招