gpt4 book ai didi

php - Mysql查询n*2格式的最大记录数

转载 作者:行者123 更新时间:2023-11-29 04:42:08 24 4
gpt4 key购买 nike

我有这样的表记录

---- ---------     ------
id name points
---- --------- ------
1 aaaa 88
2 bbbb 87
3 cccc 88
4 dddd 87
5 eeee 86
6 ffff 87
7 gggg 87
8 hhhh 85
10 iiii 86
11 iiii 86
12 iiii 86
13 iiii 86
14 iiii 86
15 iiii 86
16 iiii 87
17 iiii 82
18 hhhh 85

形成表格,我要选择符合以下条件的记录

  1. 对于第一个最高记录,最高分将排在最前面。 (但只有一个记录)。我有两条最高点88的记录,这里应该显示最近的一条(最大id)

  2. 从第二条记录开始,应以 (n*2) 的格式检索字段。我的意思是,对于第二大记录,我可以允许 4 个值相等 (2*2=4)。即表中有几个 87,但我只选择了最近的 4 条记录(最大 id)。同样对于第 3 个最大值,我可以允许 3*2=6 条记录相同..等等..

目前,我已经尝试过

select * from records group by points order by points desc

但它仅限于一条相同的记录。是否有可能根据需要在此查询中使用 count 或任何其他相关函数。希望你能帮助我。

编辑:

输出应该是这样的

---- ---------     ------
id name points
---- --------- ------
3 cccc 88 -- maximum (only one)
16 iiii 87 |
6 ffff 87 | -- 2nd maximum (allow 2*2 =4 only)
7 gggg 87 |
4 dddd 87 |
15 iiii 86 |
14 iiii 86 |
13 iiii 86 | -- 3rd maximum (allow 3*2 =6 only)
12 iiii 86 |
11 iiii 86 |
10 iiii 86 | and so on for 4th and 5th
18 hhhh 85
8 hhhh 85
17 iiii 82

最佳答案

/*Sample data*/
CREATE TABLE t
(`id` int, `name` varchar(9), `points` int)
;

INSERT INTO t
(`id`, `name`, `points`)
VALUES

('1', 'aaaa', '88'),
('2', 'bbbb', '87'),
('3', 'cccc', '88'),
('4', 'dddd', '87'),
('5', 'eeee', '86'),
('6', 'ffff', '87'),
('7', 'gggg', '87'),
('8', 'hhhh', '85'),
('10', 'iiii', '86'),
('11', 'iiii', '86'),
('12', 'iiii', '86'),
('13', 'iiii', '86'),
('14', 'iiii', '86'),
('15', 'iiii', '86'),
('16', 'iiii', '87'),
('17', 'iiii', '82'),
('18', 'hhhh', '85')
;

/*Query*/
SELECT id, name, points FROM (
SELECT
t.*
, @n := IF(@prev_points != points, @n + 1, @n) AS n
, @row := IF(@prev_points != points, 1, @row + 1) AS row
, @prev_points := points
FROM
t
, (SELECT @prev_points := null, @n := 1, @row := 0) var_init_subquery
ORDER BY points DESC, id DESC
) sq
WHERE row <= CASE WHEN n = 1 THEN 1 ELSE n * 2 END
;

/*Result*/
| ID | NAME | POINTS |
|----|------|--------|
| 3 | cccc | 88 |
| 16 | iiii | 87 |
| 7 | gggg | 87 |
| 6 | ffff | 87 |
| 4 | dddd | 87 |
| 15 | iiii | 86 |
| 14 | iiii | 86 |
| 13 | iiii | 86 |
| 12 | iiii | 86 |
| 11 | iiii | 86 |
| 10 | iiii | 86 |
| 18 | hhhh | 85 |
| 8 | hhhh | 85 |
| 17 | iiii | 82 |

关于php - Mysql查询n*2格式的最大记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26214398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com