如何按组从值列表中查询第n个值?MySQL
我有一张这样的桌子:如何按组从值列表中查询第n个值?MySQL,mysql,sql,mariadb,greatest-n-per-group,Mysql,Sql,Mariadb,Greatest N Per Group,我有一张这样的桌子: | thread_id | time | | --------- | ---------- | | 769 | 1566880174 | | 769 | 1566880415 | | 769 | 1566884409 | | 769 | 1566891158 | | 769 | 1567215554 | | 769 | 1567227195 | | 769 | 156782275
| thread_id | time |
| --------- | ---------- |
| 769 | 1566880174 |
| 769 | 1566880415 |
| 769 | 1566884409 |
| 769 | 1566891158 |
| 769 | 1567215554 |
| 769 | 1567227195 |
| 769 | 1567822758 |
| 773 | 1566973984 |
| 773 | 1567216614 |
| 773 | 1567216833 |
| 773 | 1567216913 |
| 773 | 1567216992 |
| 773 | 1567298692 |
| 774 | 1566977378 |
| 774 | 1567218446 |
| 774 | 1567228282 |
| 774 | 1568241410 |
| 784 | 1567300468 |
| 785 | 1567300549 |
| 785 | 1567310667 |
| 785 | 1567310734 |
| 785 | 1567461936 |
我需要得到按线程id分组的第n个值
| thread_id | time |
| --------- | ---------- |
| 769 | 1566880415 |
| 773 | 1567216614 |
| 774 | 1567218446 |
| 784 | null |
| 785 | 1567310667 |
我怎样才能达到这个结果
SELECT NTH_VALUE(thread_id, 2) OVER (
PARTITION BY thread_id
ORDER BY thread_id DESC
) second, time
FROM table_name;
应该是这样的,如果不工作,则显示输出您可以使用行号尝试下面的选项-
SELECT B.thread_id,C.Time
FROM (
SELECT DISTINCT thread_id FROM your_table A
)B
LEFT JOIN (
SELECT *,
@row_num :=IF(@prev_value = concat_ws('',thread_id),@row_num+1,1)AS RowNumber
, @prev_value := concat_ws('',thread_id) AS Temp
FROM your_table A,
(SELECT @row_num := 0) r
ORDER BY thread_id,`time`
)C ON B.thread_id = C.thread_id AND C.RowNumber = 2;
如果您不在MySQL 8.0上,您可以这样做(正如@Barmar所建议的):
一个更简单的解决方案可以是: [假设:
time
不是按照thread\u id
分区排序的]
这将为每个
线程id
创建一个分区,并将第二个值分配给共享相同线程id
的所有其他行。您所需要的是distinct
来删除所有重复项。我有类似的情况,但需要根据数据找到第n个值。
以下是我掌握的数据:
----------------
|id |name|score|
----------------
|1 |A |89 |
|2 |B |98 |
|3 |C |88 |
|4 |D |89 |
|5 |E |92 |
|6 |F |90 |
|7 |G |88 |
|8 |H |91 |
|9 |I |90 |
----------------
要求是找到第四高分的学生记录。我使用此查询获取基于分数的数据:
select student.id, student.name, student.score
from (select score from student group by score order by score desc limit 3,1) student_temp, student
where student_temp.score = student.score
order by student_temp.score desc ;
基于此sql,我得到了以下结果:
----------------
|id |name|score|
----------------
|6 |F |90 |
|9 |I |90 |
----------------
我有编写sql的基本知识。如果他们有任何改进或建议,请发表评论。在(分区依据…)上方放置一个行号作为内部选择,然后使用where条件获取第n个值。。。首先试一试,如果不成功,粘贴您尝试的代码如果您没有MySQL 8.0,您可以使用
GROUP\u CONCAT()
将它们连接起来,然后使用SUBSTRING\u INDEX
选择该字符串的第n个元素。根据哪个顺序查看第n个值?
select student.id, student.name, student.score
from (select score from student group by score order by score desc limit 3,1) student_temp, student
where student_temp.score = student.score
order by student_temp.score desc ;
----------------
|id |name|score|
----------------
|6 |F |90 |
|9 |I |90 |
----------------