仅返回id最高的行

时间:2014-06-24 18:30:08

标签: sql

这就是我所拥有的:

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(表ID#),但使用IN子句时,它只会为所有这4个地址提取最高表ID。我只想要最新的

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我想你想要的是每个地址的最新购买。如果这是正确的,这样的事情可能会成功:

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

答案 2 :(得分:0)

不确定我是否正确理解了这个问题。此查询将为每个地址返回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

答案 3 :(得分:0)

这个怎么样?

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