MySQL每隔两列获取前3行
Posted
技术标签:
【中文标题】MySQL每隔两列获取前3行【英文标题】:MySQL get every first 3 rows for every two other columns 【发布时间】:2021-01-18 00:45:55 【问题描述】:我想要在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
我希望我的查询返回每个 column_a
和 column_b
组合的前三行。这样最高的 3 行因子将保留。
+---+---+--------+
| a | b | factor |
+---+---+--------+
| A | X | 90 |
| A | X | 80 |
| A | X | 70 |
| A | Y | 70 |
| A | Y | 60 |
| A | Y | 50 |
+---+---+--------+
我已经找到了this 解决方案,但是这个解决方案只适用于一列而不是两列。
有什么想法吗?
【问题讨论】:
行是如何排序的?如何确定该行是第 1 行、第 2 行、....?记住 - 占有命令是不安全的。 您好,第一次订购 =column_a ASC, column_b ASC, factor DESC
【参考方案1】:
对于 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?
【讨论】:
【参考方案2】: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每隔两列获取前3行的主要内容,如果未能解决你的问题,请参考以下文章