简体   繁体   English

MySQL GROUP BY每组返回多行

[英]MySQL GROUP BY return more than one row per group

Given a sample table: 给定一个示例表:

| 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 |

I would like to return the latest N number of records for each group as below: 我想返回每个组的最新N条记录,如下所示:

Expected output: 预期产量:

| 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 |

I have this query but it only returns the latest row for each group? 我有此查询,但它只返回每个组的最新行? I would like to return more than one row (N number of rows) for each group? 我想为每个组返回多个行(N行)吗?

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

Would really appreciate some help on how I can achieve my desired output. 非常感谢您对我如何实现所需输出的帮助。 Thanks in advance. 提前致谢。

is there any way that I can get the latest N rows for each group? 有什么办法可以让每个组获取最新的N行?

Prior to the availability of row_number() you can use variables to mimic that function 在提供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

If you upgraded to MySQL 8.0, then this would solve it: 如果您升级到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;

On 5.7... I can't think of a way. 在5.7版上...我想不出办法。 :( :(

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

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