【发布时间】:2021-12-27 09:36:44
【问题描述】:
我有一张桌子,里面有很多看起来像这样的物品:
{
ID: xxx,
number: 2001,
timestamp: 2021-12-26T10:54:35.000Z,
latitude: xxx,
longitude: yyy,
-- and some more properties
},
{
ID: xxx,
number: 2001,
timestamp: 2021-12-26T10:53:39.000Z,
latitude: xxx,
longitude: yyy,
-- and some more properties
},
{
ID: xxx,
number: 2002,
timestamp: 2021-12-26T10:54:35.000Z,
latitude: xxx,
longitude: yyy,
-- and some more properties
},
{
ID: xxx,
number: 2002,
timestamp: 2021-12-26T10:55:31.000Z,
latitude: xxx,
longitude: yyy,
-- and some more properties
},
我想要做的是选择具有唯一编号和最新时间戳的所有项目。我不仅需要数字和时间戳,还需要项目的所有属性。
所以想要的输出是:
{
ID: xxx,
number: 2001,
timestamp: 2021-12-26T10:54:35.000Z,
latitude: xxx,
longitude: yyy,
-- and some more properties
},
{
ID: xxx,
number: 2002,
timestamp: 2021-12-26T10:55:31.000Z,
latitude: xxx,
longitude: yyy,
-- and some more properties
},
我使用了这个查询:
SELECT number, MAX(timestamp) FROM table GROUP BY number
它确实会选择具有唯一编号和最新时间戳的项目,但这就是问题的开始。我还需要经度和纬度以及该项目具有的所有其他属性,但是如果我尝试选择所有这些属性,则有必要在聚合函数(我不想在这里使用)或组中使用它们by,我也不想使用它,因为那样整个数据库都会被选中。
正确的做法是什么?
【问题讨论】:
-
大多数 sql DBMS 支持 window functions。用你的 DBMS 标记问题
标签: sql