如何使用 MySQL 对第三列中具有最大值的 2 列进行分组?

How do I group 2 columns with a max value in a third column using MySQL?

有了这个table.....

CREATE TABLE test
(
  id INT,
  date VARCHAR(50),
  g1 VARCHAR(50),
  stats INT
 );
 
 INSERT INTO test VALUES (1,'2002-01-01','a',2);
 INSERT INTO test VALUES (2,'2002-01-02','a',3);
 INSERT INTO test VALUES (3,'2002-01-03','a',4);
 INSERT INTO test VALUES (4,'2002-01-01','b',9);
 INSERT INTO test VALUES (5,'2002-01-02','b',8);
 INSERT INTO test VALUES (6,'2002-01-03','b',7);
 INSERT INTO test VALUES (7,'2002-01-01','c',6);
 INSERT INTO test VALUES (8,'2002-01-02','c',9);
 INSERT INTO test VALUES (9,'2002-01-03','c',5);

我想得到以下结果。

date g1 MAX(stats)
2002-01-03 a 4
2002-01-01 b 9
2002-01-02 c 9

我有这个问题。但是添加日期列一直具有挑战性。

SELECT g1, MAX(stats)
FROM test
GROUP BY g1

请帮忙。谢谢。

如果你的 mysql 版本支持 ROW_NUMBER window 功能你可以试试这个。

SELECT *
FROM (
 SELECT *,ROW_NUMBER() OVER(PARTITION BY g1 ORDER BY stats DESC) rn
 FROM test
) t1
WHERE rn = 1

EXISTS子查询

SELECT *
FROM test t1
WHERE EXISTS (
    SELECT 1
    FROM test tt
    WHERE tt.g1 = t1.g1
    HAVING MAX(tt.stats) = t1.stats
)

sqlfiddle

额外的连接应该可以工作,我在这里使用了 CTE 样式,但您也可以使用子查询。

WITH temp as (SELECT g1, MAX(stats) as stats
FROM test
GROUP BY g1)
SELECT test.date, temp.g1, temp.stats FROM test INNER JOIN temp ON temp.stats = test.stats AND temp.g1 = test.g1;

https://www.db-fiddle.com/f/cvq37zrwEtdHNnQTbJydHK/0