/*
分组取最小值的例子
找出表中条件为flag=0的,按typeid分组,取title字母最小的一条记录。
*/
if object_id('tempdb..#A', 'u') is not null
drop table #A
go
create table #A([id] int,typeid int,title varchar(5),flag int)
go
insert into #A([id],typeid,title,flag)
select 1 ,0 , 'a' , 0
union all
select 2 , 0 , 'b' , 1
union all
select 3 , 0 , 'c' , 0
union all
select 4 , 1 , 'd' , 1
union all
select 5 , 1 , 'e' , 0
union all
select 6 , 2 , 'f' , 1
union all
select 7 , 3 , 'g' , 0
go
select a.*
from #A a,
(
select typeid,title=min(title)
from #A
where flag=0
group by typeid
) b
where a.typeid=b.typeid and a.title=b.title
order by a.title
分组取最小值的例子
找出表中条件为flag=0的,按typeid分组,取title字母最小的一条记录。
*/
if object_id('tempdb..#A', 'u') is not null
drop table #A
go
create table #A([id] int,typeid int,title varchar(5),flag int)
go
insert into #A([id],typeid,title,flag)
select 1 ,0 , 'a' , 0
union all
select 2 , 0 , 'b' , 1
union all
select 3 , 0 , 'c' , 0
union all
select 4 , 1 , 'd' , 1
union all
select 5 , 1 , 'e' , 0
union all
select 6 , 2 , 'f' , 1
union all
select 7 , 3 , 'g' , 0
go
select a.*
from #A a,
(
select typeid,title=min(title)
from #A
where flag=0
group by typeid
) b
where a.typeid=b.typeid and a.title=b.title
order by a.title