MySQL GROUP BY每组返回多行

时间:2018-09-07 07:35:54

标签: mysql group-by

给出示例表:

| id | locationID |      Date_Time      | temp |
|----|------------|---------------------|------|
| 1  | L001       | 2018-09-04 11:25:00 | 52.6 |
| 2  | L002       | 2018-09-04 11:35:00 | 66.1 |
| 3  | L003       | 2018-09-04 03:30:00 | 41.2 |
| 4  | L003       | 2018-09-05 10:22:00 | 71.8 |
| 5  | L003       | 2018-09-06 14:21:00 | 63.4 |
| 6  | L003       | 2018-09-06 18:18:00 | 50.1 |

我想返回每个组的最新N条记录,如下所示:

预期输出:

| id | locationID |      Date_Time      | temp |
|----|------------|---------------------|------|
| 1  | L001       | 2018-09-04 11:25:00 | 52.6 |
| 2  | L002       | 2018-09-04 11:35:00 | 66.1 |
| 4  | L003       | 2018-09-05 10:22:00 | 71.8 |
| 5  | L003       | 2018-09-06 14:21:00 | 63.4 |
| 6  | L003       | 2018-09-06 18:18:00 | 50.1 |

我有此查询,但它只返回每个组的最新行?我想为每个组返回多于一行(N行数)吗?

SELECT *
FROM HealthStatus
WHERE Date_Time IN (
    SELECT MAX(Date_Time)
    FROM HealthStatus
    GROUP BY LocationID
)

非常感谢您提供一些有关如何实现所需输出的帮助。预先感谢。

2 个答案:

答案 0 :(得分:2)

有什么方法可以获取每个组的最新N行吗?

在row_number()可用之前,您可以使用变量来模仿该功能

SELECT
*
FROM (
    SELECT
          @row_num :=IF(@prev_value=locationID,@row_num+1,1)AS RowNumber
        , id , locationID , Date_Time,temp
        , @prev_value := locationID
    FROM HealthStatus
    CROSS JOIN (SELECT @row_num :=1,  @prev_value :='') vars
    ORDER BY
          locationID , Date_Time DESC
    ) derived
WHERE RowNumber < 4

答案 1 :(得分:1)

如果升级到MySQL 8.0,则可以解决该问题:

SELECT * FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY locationID ORDER BY Date_Time DESC) AS r
  FROM HealthStatus
) T
WHERE r <= 3;

关于5.7 ...我想不出办法。 :(