我有一个类似下面的表(此表称为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 |
+----+---------------------+---------+-----------------------+-------+-------------+
我要选择具有两个条件的行。
unique as_id, codename
组合的行所以,这里我独特的组合是
1795, ActivePower
1795, Cumulative
+----+---------------------+---------+-----------------------+-------+-------------+
| 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 |
+----+---------------------+---------+-----------------------+-------+-------------+
答案 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