mysql-选择最新值,其中

时间:2019-03-15 06:50:47

标签: mysql sql group-by max

我有一个类似下面的表(此表称为t1)

+----+---------------------+---------+-----------------------+-------+-------------+
| id | timestamp           | p_value | TS                    | as_id | codename    |
+----+---------------------+---------+-----------------------+-------+-------------+
| 1  | 2019-03-13 07:55:44 | 561     | 2019-03-13 09:14:31   | 1795  | ActivePower |
+----+---------------------+---------+-----------------------+-------+-------------+
| 2  | 2019-03-13 07:55:44 | 561     | 2019-03-13 07:53:17   | 1795  | ActivePower |
+----+---------------------+---------+-----------------------+-------+-------------+
| 3  | 2019-03-13 07:55:45 | 561     | 2019-03-13 07:53:17   | 1795  | ActivePower |
+----+---------------------+---------+-----------------------+-------+-------------+
| 4  | 2019-03-13 07:55:48 | 974     | 2019-03-13 07:33:21   | 1795  | Cumulative  |
+----+---------------------+---------+-----------------------+-------+-------------+
| 5  | 2019-03-13 07:56:26 | 974     | 2019-03-13 07:33:28   | 1795  | Cumulative  |
+----+---------------------+---------+-----------------------+-------+-------------+

我要选择具有两个条件的行。

  1. 获取包含unique as_id, codename组合的行

所以,这里我独特的组合是

1795, ActivePower
1795, Cumulative
  1. 按最大时间戳值过滤,如果最大时间戳相同,则按id desc排序,限制为1。因此,我可以获得最新的行。

预期输出:

+----+---------------------+---------+-----------------------+-------+-------------+
| id | timestamp           | p_value | TS                    | as_id | codename    |
+----+---------------------+---------+-----------------------+-------+-------------+
| 3  | 2019-03-13 07:55:44 | 561     | 2019-03-13 07:53:17   | 1795  | ActivePower |
+----+---------------------+---------+-----------------------+-------+-------------+
| 5  | 2019-03-13 07:56:26 | 974     | 2019-03-13 07:33:28   | 1795  | Cumulative  |
+----+---------------------+---------+-----------------------+-------+-------------+

3 个答案:

答案 0 :(得分:0)

使用相关的子查询

  select t1.* from table_name t1
  where (t1.timestamp,id) in ( select max(timestamp),max(id) from 
                       table_name t2 where t1.as_id=t2.as_id
                       and t1.codename=t2.codename
                       )

答案 1 :(得分:0)

使用相关子查询

select * from tablename a
where id in 
    (select max(id) from tablename b where a.as_id=b.as_id and a.codename=b.codename)

答案 2 :(得分:0)

您可以通过ROW_NUMBER()

实现
SELECT  id, timestamp, p_value, TS, as_id, codename 
FROM (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY as_id, codename ORDER BY TS DESC) AS RN
    FROM Table
) AS Q
WHERE RN = 1