如何在mysql中找到一个字段和组的最大值

时间:2014-11-10 21:32:09

标签: mysql

I am trying to find the max of a count1 field and group it by sname

我有下表有4列,我想要最多count1并按sname分组。 count1的最大值给了我最大值,但当我按sname进行分组时,它会使用错误的cname和sname。       我期待的是s1 c2 30和s2 c1 40.任何人都可以帮我解决mysql查询

2 个答案:

答案 0 :(得分:0)

SELECT g.sname AS sname, g.cname AS cname, g.count1 AS total 
FROM giriya AS g
   INNER JOIN (SELECT cname, MAX(count1) AS countMax GROUP BY cname) AS ss
   ON g.cname = ss.cname AND g.count1 = ss.countMax

答案 1 :(得分:0)

SELECT g.sname,g.cname,g.count1 AS total FROM giriya AS g INNER JOIN(来自giriya GROUP BY cname的SELECT cname,MAX(count1)AS countMax)AS ss  ON g.cname = ss.cname和g.count1 = ss.countMax