根据sql查询中的条件查找值对

时间:2014-08-22 08:12:41

标签: mysql sql

我有样本查询 SQL Fiddle。我需要找到对值(a,1),(c,2),因为对于它们列 SomeCount 具有最高值。谢谢 ; )

2 个答案:

答案 0 :(得分:1)

select SomeName, SerialNo
from testTable
group by SerialNo -- because you want to have the biggest result of SomeCount from a set of rows with the same SerialNo
order by SomeCount DESC -- because you want to have the result with the biggest SomeCount

答案 1 :(得分:1)

使用联接获取分组最大行的两种方法我假设SerialNo为一组

方法1

使用左连接

select concat(t.SomeName,',',t.SerialNo) pair
,t.*
from testTable t
left join testTable t1 
     on(t.SerialNo = t1.SerialNo
        and t.SomeCount < t1.SomeCount)
WHERE t1.SerialNo IS NULL;

方法2

使用内部联接和子选择

select concat(t.SomeName,',',t.SerialNo) pair
,t.*
from testTable t
join (select SerialNo ,max(SomeCount) SomeCount 
      from testTable
     group by SerialNo) t1 
on(t.SerialNo = t1.SerialNo  and t.SomeCount = t1.SomeCount)

Fiddle demo

Group-wise Maximum of a Certain Column