MySQL 每隔两列获取前 3 行

MySQL get every first 3 rows for every two other columns

我在 mysql 中试图实现的目标如下:

我有一个 table 包含以下数据:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(a CHAR(1) NOT NULL
,b CHAR(1) NOT NULL
,factor INT NOT NULL
,PRIMARY KEY(a,b,factor)
);

INSERT INTO my_table VALUES
('A','X',90), -- should be included
('A','X',80), -- should be included
('A','X',70), -- should be included
('A','X',60), -- should NOT be included
('A','Y',70), -- should be included
('A','Y',60), -- should be included
('A','Y',50), -- should be included
('A','Y',40); -- should NOT be included

我想要查询 return 每个 column_acolumn_b 组合的前三行。这样最高的3行因子就会保留下来。

+---+---+--------+
| a | b | factor |
+---+---+--------+
| A | X |     90 |
| A | X |     80 |
| A | X |     70 |
| A | Y |     70 |
| A | Y |     60 |
| A | Y |     50 |
+---+---+--------+

我已经找到 this 解决方案,但这个解决方案只适用于一列而不是两列。

有什么想法吗?

WITH cte AS ( SELECT *, 
                     ROW_NUMBER() OVER ( PARTITION BY column_a, column_b 
                                         ORDER BY  factor DESC ) rn
              FROM table )
SELECT column_a, column_b, factor
FROM cte 
WHERE rn <= 3;

对于 MySQL 8.0 之前的版本...

SELECT x.*
  FROM my_table x 
  JOIN my_table y 
    ON y.a = x.a 
   AND y.b = x.b 
   AND y.factor >= x.factor 
 GROUP 
    BY x.a
     , x.b
     , x.factor 
HAVING COUNT(*) <= 3 
 ORDER 
    BY a
     , b
     , factor DESC;

...下一次,请看:Why should I provide an MCRE for what seems to me to be a very simple SQL query?