构建查询以查找最近两个小时内具有唯一 ID 的最新行
Constructing a Query to find the newest rows within the last two hours with with a unique id
我正在尝试 select 过去两个小时内每个唯一数据->>Id 的所有最新行(基于时间列)。
数据列是 json 列,应使用箭头运算符访问。
Id Time Data
1 2020-08-13 18:13:14 {'Id': "1"}
2 2020-08-13 18:14:12 {'Id': "2"}
3 2020-08-13 18:14:19 {'Id': "1"}
4 2020-08-13 17:13:21 {'Id': "2"}
5 2020-08-13 18:23:54 {'Id': "1"}
6 2020-08-13 13:13:21 {'Id': "2"}
结果应该是这样的,当前时间是 2020-08-13 18:15:00
Id Time Data
1 2020-08-13 18:13:14 {'Id': "1"}
4 2020-08-13 17:13:21 {'Id': "2"}
您可以使用 distinct on
:
select distinct on (data) t.*
from t
order by data, time desc;
使用 distinct on
和 json 访问器:
select distinct on (data ->> 'id') t.*
from mytable t
order by data ->> 'id', time desc
我正在尝试 select 过去两个小时内每个唯一数据->>Id 的所有最新行(基于时间列)。 数据列是 json 列,应使用箭头运算符访问。
Id Time Data
1 2020-08-13 18:13:14 {'Id': "1"}
2 2020-08-13 18:14:12 {'Id': "2"}
3 2020-08-13 18:14:19 {'Id': "1"}
4 2020-08-13 17:13:21 {'Id': "2"}
5 2020-08-13 18:23:54 {'Id': "1"}
6 2020-08-13 13:13:21 {'Id': "2"}
结果应该是这样的,当前时间是 2020-08-13 18:15:00
Id Time Data
1 2020-08-13 18:13:14 {'Id': "1"}
4 2020-08-13 17:13:21 {'Id': "2"}
您可以使用 distinct on
:
select distinct on (data) t.*
from t
order by data, time desc;
使用 distinct on
和 json 访问器:
select distinct on (data ->> 'id') t.*
from mytable t
order by data ->> 'id', time desc