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

求解最小值问题
create table #T(name char(10),id char(1),countx  int)
insert into #T 
select 'A','1',20
union
select 'A','2',30
union
select 'B','1',30
union
select 'B','2',20
union
select 'C','1',40

select #t.name,#t.id,#t.countx from #T inner join 
(select name,min(id) id from #t group by name) b
on #T.name=b.name and #T.id=b.id

drop table #T

上面需要进行inner join 连接才能完成
有没有更好的方法,更简洁的方法

------解决方案--------------------

create table #T(name char(10),id char(1),countx  int)
insert into #T 
select 'A','1',20
union
select 'A','2',30
union
select 'B','1',30
union
select 'B','2',20
union
select 'C','1',40

select * from #T a
where a.id=(select MIN(id) from #T b where a.name=b.name)
/*
name id countx
----------------------------
A          1 20
B          1 30
C          1 40
*/

------解决方案--------------------
SELECT * 
FROM #T AS t1 
WHERE NOT EXISTS(SELECT 1 FROM #T AS t2 WHERE t1.name = t2.name AND t1.id > t2.id)

name       id   countx
---------- ---- -----------
A          1    20
B          1    30
C          1    40

------解决方案--------------------
select * from #T a
where a.id=(select MIN(id) from #T b where a.name=b.name)