【问题标题】:Selecting unique items in SQL based on some of the properties根据某些属性在 SQL 中选择唯一项
【发布时间】: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


【解决方案1】:

partition by的简单使用

select *
from (
select row_number() over (partition by number order by timestampp desc) as ordering, timestampp, id, number, latitude, longitude
from tbl) x
where ordering = 1

【讨论】:

    【解决方案2】:
    select *
    from (
    select row_number() over (partition by timestamp, number order by timestamp desc) as ordering, id, number, latitude, longitude
    from my_table)
    where ordering = 1
    

    【讨论】:

      【解决方案3】:

      您可以使用 DISTINCT :

      SELECT id, DISTINCT(number), * 
      FROM yourtable
      WHERE MAX(timestamp)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-21
        • 1970-01-01
        • 2012-04-17
        • 2022-09-23
        • 2017-08-20
        • 1970-01-01
        • 1970-01-01
        • 2013-05-02
        相关资源
        最近更新 更多