如何根据一列的最大值从MySQL中选择行并将另外两列分组?该查询需要按代码分组,按带有where子句(element_id = 1.B.1.b)和max(data_value)的element_id分组.
code element_id data_value
11-1011.00 1.B.1.a 1.33
11-1011.00 1.B.1.b 2.00
11-1012.00 1.B.1.a 2.67
11-1012.00 1.B.1.b 3.67
11-1012.00 1.B.1.C 7.00
我已经试过了:
SELECT * FROM (select
max(`data_value`) as maxID, `code`, `element_id`
from
table_name
GROUP BY `code`, `element_id`
ORDER BY maxID desc) abc
GROUP BY `code`
在那张桌子上,我有很多数据.它是一个样本.
在这里您可以看到更清晰的信息:
我需要结果:
11-1011.00 1.B.1.b 2.00
11-1012.00 1.B.1.c 7.00
这个结果无处可寻.
如果使用where子句,我只希望有一个与element_id(1.B.1.b)匹配的结果,我具有:
11-1011.00 1.B.1.b 2.00
解决方法:
您可以通过实现
SELECT a.code, max( a.maxID ) , a.element_id
FROM (
SELECT *
FROM (
SELECT max(data_value) AS maxID, code , element_id
FROM table_name
GROUP BY code , element_id
ORDER BY maxID DESC
) AS abc
GROUP BY code
) AS a
WHERE a.element_id = '1.B.1.b'
GROUP BY a.code
ORDER BY a.code
或尝试这个
SELECT a.code, a.element_id, a.data_value
FROM interests a
INNER JOIN (
SELECT code, max( data_value ) data_value
FROM table_name
GROUP BY code
)b ON a.code = b.code
AND a.data_value = b.data_value
WHERE a.element_id = '1.B.1.b'
ORDER BY a.code