如何查询表中每个组的前n条记录?

时间:2019-06-27 13:13:21

标签: mysql stored-procedures

我有一个日志表,其中有host_name,drive_id和process_run_id作为主键。

我需要MySQL语句,该语句将为每个唯一的host_name和drive_id获得前n个process_run_id。

当前表:

|host_name|drive_id |process_run_id|free_space|
|       A |   C     |          1   |       500|
|       A |   C     |          2   |       500|
|       A |   C     |          3   |       570|
|       A |   C     |          4   |      1000|
|       B |   C     |          1   |       769|
|       B |   C     |          2   |      4167|
|       B |   C     |          3   |      3244|
|       B |   D     |          1   |      7654|
|       B |   D     |          2   |        76|
|       B |   D     |          3   |       435|
|       B |   D     |          4   |       243|
|       C |   C     |          1   |     23443|
|       C |   C     |          2   |      4324|
|       C |   C     |          3   |      1232|
|       C |   C     |          4   |      9777|

所需查询结果(排名前2):

|host_name|drive_id |process_run_id|free_space|
|       A |   C     |          3   |       570|
|       A |   C     |          4   |      1000|
|       B |   C     |          2   |      4167|
|       B |   C     |          3   |      3244|
|       B |   D     |          3   |       435|
|       B |   D     |          4   |       243|
|       C |   C     |          3   |      1232|
|       C |   C     |          4   |      9777|

尝试:

SELECT space_free, host_name, drive_id, process_run_id
FROM
(SELECT space_free, host_name, drive_id, process_run_id,
              @host_rank := IF(@current_host = CONCAT(host_name, drive_id), @host_rank + 1, 1) AS host_rank,
              @current_host := CONCAT(host_name, drive_id)
   FROM sandbox_yohal.main_fds_history_list
   ORDER BY host_name, process_run_id DESC
 ) ranked
WHERE host_rank <= 2;

1 个答案:

答案 0 :(得分:1)

SELECT host_name, drive_id, process_run_id, space_free, space_total, date_processed
FROM
(SELECT host_name, drive_id, process_run_id, space_free, space_total, date_processed,
          @host_rank := IF(@current_host = CONCAT(host_name, drive_id), @host_rank + 1, 1) AS host_rank,
          @current_host := CONCAT(host_name, drive_id)
   FROM main_fds_history_list
CROSS JOIN(SELECT @host_rank := NULL, @current_host := NULL) AS init_user_param 
   ORDER BY CONCAT(host_name, drive_id), process_run_id DESC) ranked
WHERE host_rank <= 2;

感谢@RaymondNijland