如何在SQL中获得两个不同的记录

时间:2018-06-11 14:56:19

标签: sql sql-server sql-server-2008

我有地址表,我正在尝试根据AddressType_ID选择最大ID 2行(AddressType_ID是物理或邮件类型。物理值为1,邮件有值2)您能否指导我一个逻辑。

Address_id  Foreign_Key  AddressLine1     Addresstype_id
1849        1854         182 SE 136th Rd         1
3287        1854         PO Box 285              2
32330       1854         182 SE 139th Rd         1
32331       1854         PO Box 288              2

我试图在addresstype_Id上选择地址ID 32330和32331的所有列值。获得这两个记录的逻辑是什么?

3 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你需要两行 - 一个用于给定外键的每个地址类型id,该外键应具有最新的地址id数据

在这种情况下,使用ROW_NUMBER()窗口函数

使用以下查询
select 
Address_id,
Foreign_Key,
AddressLine1,
Addresstype_id
from
(
select 
*, 
rn= row_number() over( partition by foreign_key,type order by address_id desc)
from youraddresstable
) t
where rn= 1

答案 1 :(得分:0)

您可以使用UNION

SELECT TOP (1)
Address_id, Foreign_Key, AddressLine1, Addresstype_id
FROM yourAddressTable
WHERE Addresstype_id = 1
ORDER BY Address_id DESC

UNION ALL

SELECT TOP (1)
Address_id, Foreign_Key, AddressLine1, Addresstype_id
FROM yourAddressTable
WHERE Addresstype_id = 2
ORDER BY Address_id DESC

答案 2 :(得分:0)

你可以使用row_number()函数和tie ...方法:

select top (1) with ties, *
from table t
order by row_number() over (partition by foreign_key,type order by address_id desc);

但是,我发现你有PKaddress_id,那么你也可以用相关方法表示为子查询:

select t.*
from tabel t
where address_id = (select max(t1.address_id) 
                    from table t1 
                    where t1.foreign_key = t.foreign_key and t1.type = t.type 
                   );
相关问题