简体   繁体   English

ORDER BY后如何使用ROW_NUMBER()函数mysql?

[英]How to use ROW_NUMBER() function mysql after the ORDER BY?

SELECT user.id
      ,user.emp_id
      ,user.name,COUNT(transfer.record_name) AS current_rank
      ,ROW_NUMBER() OVER () AS count
FROM transfer AS transfer
LEFT JOIN users AS user ON user.emp_id= transfer.user_id
WHERE transfer.lobs= 0
AND transfer.shift_date = '2020-03-27'
GROUP BY user.emp_id
ORDER BY current_rank DESC

This query will give me a result of like this:这个查询会给我这样的结果:

user.id|   user.emp_id|   user.name|   current_rank|   count
25           1234          test1           4             4
30           4321          test2           2             2
18           5678          test3           1             1
12           8765          test4           1             3

My goal is to use ORDER BY DESC first so that I can order the current_rank and the count column should have the count of:我的目标是首先使用 ORDER BY DESC 以便我可以对current_rank进行排序,并且count列应该具有以下计数:

user.id|   user.emp_id|   user.name|   current_rank|   count
25           1234          test1           4             1
30           4321          test2           2             2
18           5678          test3           1             3
12           8765          test4           1             4

How can I use the ROW_NUMBER() function after I ORDER BY my current_rank column?在按current_rank列排序后,如何使用 ROW_NUMBER() 函数?

Thank you any help.谢谢你的任何帮助。 I will appreciate it.我会很感激的。

The result of ROW_NUMBER() is not affected by the sort in the query. ROW_NUMBER()的结果不受查询中排序的影响。

Instead, it accepts an ORDER BY option within its OVER clause: without it, the ordering of ROW_NUMBER() is undefined , meaning that the database is free to order the rows as it likes.相反,它在其OVER子句中接受ORDER BY选项:没有它, ROW_NUMBER()的排序是undefined ,这意味着数据库可以随意对行进行排序。 You may observe that the same ordering is used over consecutive executions, but the database does not guarantee it.您可能会观察到在连续执行中使用相同的顺序,但数据库并不能保证这一点。

So, do add an ORDER BY to the window function:所以,一定要在窗口函数中添加一个ORDER BY

ROW_NUMBER() OVER (ORDER BY COUNT(transfer.record_name) DESC) AS count

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM