Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL每隔两列获取前3行_Mysql_Sql_Greatest N Per Group_Window Functions - Fatal编程技术网

MySQL每隔两列获取前3行

MySQL每隔两列获取前3行,mysql,sql,greatest-n-per-group,window-functions,Mysql,Sql,Greatest N Per Group,Window Functions,我试图在mysql中实现以下目标: 我有一个包含以下数据的表格: 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',

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

我有一个包含以下数据的表格:

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
我希望我的查询在列A和列b的组合中每前三行返回一次。因此,最高的3行因子将保持不变

+---+---+--------+
| a | b | factor |
+---+---+--------+
| A | X |     90 |
| A | X |     80 |
| A | X |     70 |
| A | Y |     70 |
| A | Y |     60 |
| A | Y |     50 |
+---+---+--------+
我已经找到了解决方案,但这一个只适用于一列,而不是两列

有什么想法吗?

选择cte*, 按列a、列b分区的行数 按系数顺序描述 从桌子上 选择列a、列b、系数 来自cte
其中rn对于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;

…关于下一次,请参见:

行是如何排序的?如何确定行是第一行、第二行?记住-顺序不安全。嗨,第一顺序=列a ASC,列b ASC,因子描述