【问题标题】:return only the rows with highest id只返回 id 最高的行
【发布时间】:2014-08-15 03:19:02
【问题描述】:

这就是我所拥有的:

select *
from table
where address1 in ('1235 mary st', '516 fred way', '89 valley st', '5416 apple ave')
order by name

结果集返回这 4 个地址的 100 条记录(此表类似于购买表),并且此表的每一行都有一个 ID#,但我只想提取 ID# 最高的行。希望这是足够的信息。

我认为只使用 max(table ID#) 但使用 IN 子句它只为所有 4 个地址提取最高的表 ID。我只想要最新的

【问题讨论】:

  • order by id desc 然后使用您使用的任何数据库引擎获取第一个条目。对于 MySQL,它是 limit 1,对于 MSSQL,它是 top 1
  • 每个地址是否需要恰好一行?

标签: sql


【解决方案1】:

在支持窗口函数的数据库上,您可以使用row_number() 为每个地址分配递增的数字:

select  *
from    ( 
        select  row_number() over (partition by address1
                                   order by id desc) as rn
        ,       *
        from    table
        where   address1 in (...)
        ) SubQueryAlias
where   rn = 1 -- Only latest row per address

【讨论】:

  • SELECT distinct * FROM cust AS C WHERE internalid IN (SELECT DISTINCT customerid FROM purch as p WHERE ADDRESS1 不是 NULL AND ADDRESS1 IN (SELECT DISTINCT ADDRESS1 FROM Address AS A WHERE customerid not in (SELECT distinct customerid FROM Customer AS C WHERE C.CUSTOMERID=A.CUSTOMERID)))....当我将 address1 与 purch 表进行比较时,那是我得到大量额外记录的时候,而实际上我只是想追踪来自底部子查询的杂散记录回到购买表
【解决方案2】:

我认为您想要的是每个地址的最新购买。如果这是正确的,这样的事情可能会奏效:

select top 1 *
from table
where address1 = '1235 mary st'
order by id desc

UNION ALL

select top 1 *
from table
where address1 = '516 fred way'
order by id desc

UNION ALL

select top 1 *
from table
where address1 = '89 valley st'
order by id desc

UNION ALL

select top 1 *
from table
where address1 = '5416 apple ave'
order by id desc

【讨论】:

    【解决方案3】:

    不确定我是否正确理解了这个问题。此查询将为每个地址返回 1 行以及该地址的最大 id。

    select max(id), address1
    from table
    where address1 in ('1235 mary st', '516 fred way', '89 valley st', '5416 apple ave')
    group by address1
    

    【讨论】:

    • 对不起,我的原始帖子是我正在使用的 lil 测试查询。我有一个更大的查询,里面有几个子查询。我试图通过address1列将2个表之间的杂散记录追溯到历史表,但是当我这样做时,我得到了与该address1相关的所有事务,这是我不想要的。我只想要最近的,我认为我可以通过该历史表中的 ID 提取。抱歉我的帖子搞砸了。感谢您的帮助
    【解决方案4】:

    这个怎么样?

    SELECT MAX(ID) AS MaxId, address1
    FROM table
    WHERE address1 in ('1235 mary st', '516 fred way', '89 valley st', '5416 apple ave')
    GROUP BY address1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 2023-03-03
      • 2022-01-13
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多