日期:2014-05-18 浏览次数:20695 次
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test]([id] int,[ba] int,[zc] int,[name] varchar(4))
insert [test]
select 1,1111,1,'小明' union all
select 2,1111,2,'小明' union all
select 3,1111,3,'小明' union all
select 4,2222,1,'小丽' union all
select 5,2222,2,'小丽' union all
select 6,3333,1,'小红'
select * from test a
where a.zc=(select MIN(zc) from test b where a.ba=b.ba)
/*
id ba zc name
--------------------------------
1 1111 1 小明
4 2222 1 小丽
6 3333 1 小红
*/
------解决方案--------------------
select * from test t where not exists(select 1 from test whereba=t.ba and zc<t.zc)
------解决方案--------------------
select id,ba,zc,name from(
select px=ROW_NUMBER()over(partition by ba order by zc asc),
* from test--这个查询返回的是按照ba分组,zc递增排序
)t
where px=1--取出每个分组的排序为1(px=1)的数据