如果一个表,有三个字段 id、value、category ,如何写 sql 查询每个 category 中 value 最大的记录的 id
得用子查询了
select id, category, max(value) from t group by category;
max(value) 查出来不用就行了
SELECT
category,
id
FROM
test_table
WHERE
_value IN (
SELECT
max( _value )
FROM
test_table
GROUP BY
category)
select * from (select id, category, value from t order by category, value desc) b group by b.category;
SELECT
a.id,
a.category
FROM
t a
INNER JOIN ( SELECT category, MAX( `value` ) AS 'value' FROM t GROUP BY category ) AS b ON a.category = b.category
AND a.`value` = b.`value`
有什么方法可以不用到 group by 语句吗
可以用 row_number() over(partition by category order by value desc) 结合子查询
select id from category
where concat(value,category) in
(select concat(max(value),category) from table a
group by category)
SELECT
P.id,
P.`value`,
P.category
FROM
table_p AS P
INNER JOIN ( SELECT MAX(`value`) AS M, category FROM table_p GROUP BY category ) AS P1
WHERE
P1.M = P.`value`
AND P1.category = P.category
GROUP BY
P.category
如果最大值有多个需要同时保留就不要最后的 group by
===> 什么数据库呢?
如果 mysql , Tester_谜城 的完全正确。
如果其他数据库 (如 oracle,sqlserver) ,要求 value 最大有几个并且只保留第一个的话要复杂些。
可以妙用 exists,select d.name Department,e.name Employee,e.Salary from Employee e join Department d on e.DepartmentId = d.Id where not exists(select * from Employee c where e.DepartmentId = c.DepartmentId and c.Salary > e.Salary) https://leetcode-cn.com/problems/department-highest-salary/
SELECT category,id
FROM table
WHERE value IN (
SELECT max( value )
FROM table
GROUP BY category)
mysql 中相关子查询可以搞定,不需要分组
select * from (select * from categorys order by value desc) c group by category;
或者
select distinct(category), value from (select * from categorys order by value desc) c;