日期:2014-05-18  浏览次数:20577 次

同一张表中对数据分组求某列最大值的问题
同一张表中怎么对数据分组求某列最大值,如果最大值有并列项则取id最小的那一行数据

------解决方案--------------------
假设以name分组
SQL code
select * from tb t
where not exists(select 1 from tb where name=t.name and (value>t.value or value=t.value and id<t.id)

------解决方案--------------------
SQL code

-----------刚刚看错题目了

create table stu(id int,[name] varchar(10),val int)
insert into stu
select 1,'a',2 union all
select 2,'a',2 union all
select 3,'b',4 union all
select 4,'b',4 

select * from stu where id in(
select id from (select min(id) as id,max(val) as val from stu group by val)tmp)

--------------------------------------------

id          name       val
----------- ---------- -----------
1           a          2
3           b          4

(2 行受影响)