有没有一种方法可以在MySQL中基于列a和B对结果进行排序,然后将结果限制为每个值a的X,如ORDER BY A, (B LIMIT X)
?
假设我有以下格式的表:
+------+--------+------+
| Col1 | Col2 | Col3 |
+------+--------+------+
| A | 100 | abc |
| A | 200 | acd |
| A | 300 | atd |
| A | 400 | aem |
| A | 500 | ieb |
| B | 150 | aio |
| B | 250 | loe |
| B | 350 | wmd |
| B | 450 | zir |
| B | 550 | oui |
+------+--------+------+
我想获得与列1的每个值相关联的列2的X最大值。下面是一个结果示例,如果我想让每个col1结果都排在前3位:
+------+--------+------+
| Col1 | Col2 | Col3 |
+------+--------+------+
| A | 500 | ieb |
| A | 400 | aem |
| A | 300 | atd |
| B | 550 | oui |
| B | 450 | zir |
| B | 350 | wmd |
+------+--------+------+
如果不依赖列1的每个值一个查询,我如何实现这种行为?
最佳答案
试试这个;)
SQL Fiddle
CREATE TABLE table_A
(`Col1` varchar(1), `Col2` int, `Col3` varchar(3))
;
INSERT INTO table_A
(`Col1`, `Col2`, `Col3`)
VALUES
('A', 100, 'abc'),
('A', 200, 'acd'),
('A', 300, 'atd'),
('A', 400, 'aem'),
('A', 500, 'ieb'),
('B', 150, 'aio'),
('B', 250, 'loe'),
('B', 350, 'wmd'),
('B', 450, 'zir'),
('B', 550, 'oui')
;
问题1:
select a.*
from table_A a
left join table_A b on a.Col1 = b.Col1 and a.Col2 <= b.Col2
group by a.Col1,a.Col2,a.Col3
having count(*) <=3
order by a.Col1 asc, a.Col2 desc
Results:
| Col1 | Col2 | Col3 |
|------|------|------|
| A | 500 | ieb |
| A | 400 | aem |
| A | 300 | atd |
| B | 550 | oui |
| B | 450 | zir |
| B | 350 | wmd |