问答 请教一个 sql 查询问题

endno3 · 2021年06月02日 · 最后由 知识分子 回复于 2021年07月21日 · 3690 次阅读

如果一个表,有三个字段 id、value、category ,如何写 sql 查询每个 category 中 value 最大的记录的 id

共收到 20 条回复 时间 点赞

得用子查询了

恒温 回复

select id, category, max(value) from t group by category;
max(value) 查出来不用就行了

槽神 回复

这样查不出 id 吧

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) 结合子查询

endno3 回复

嗯,查不出

10楼 已删除

select id from category
where concat(value,category) in
(select concat(max(value),category) from table a
group by category)

MarvinWu 回复

如果不同的 category 的 max(value)是相同的怎么办

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

14楼 已删除

===> 什么数据库呢?
如果 mysql , Tester_谜城 的完全正确。
如果其他数据库 (如 oracle,sqlserver) ,要求 value 最大有几个并且只保留第一个的话要复杂些。

endno3 #17 · 2021年06月03日 Author
ysir 回复

是 MySQL,如果是其他数据库会有什么不同

可以妙用 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/

孤灯 回复

666

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;

需要 登录 後方可回應,如果你還沒有帳號按這裡 注册