sql查询获取一个人的许多地址的一个地址

时间:2014-02-07 12:20:03

标签: sql

两个表:人和地址; join condition是addresses.key_value = person.person_id。

有三个地址.address_type:'R','M','T'。

获取person.first_name,addresses.address_1,addresses.zip,addresses.state

如果address_type'T'然后获取'T'的地址,否则如果'M',则'R'。

对于每个地址,地址表中都有唯一的address_id。

2 个答案:

答案 0 :(得分:0)

如果您使用sqlserver 2005+,这可能是您的解决方案:

select * from person p
--cross apply instead of outer apply if you only want people with addresses
outer apply
(select top 1 with ties * from addresses where p.person_id = key_value
order by case address_type when 'T' then 1 when 'M' THEN 2 WHEN 'R' THEN 3 END
) a

答案 1 :(得分:0)

您希望优先处理地址。大多数数据库都支持窗口/分析功能,并提供了一种机制:

select p.first_name, a.address_1, a.zip, a.state
from person p join
     (select a.*,
             row_number() over (partition by a.person_id
                                order by (case when a.address_type = 'T' then 1
                                               when a.address_type = 'M' then 2
                                               when a.address_type = 'R' then 3
                                          end)
                               ) as seqnum
      from addresses a
     ) a
     on p.person_id = a.person_id and seqnum = 1;

编辑:

如果您想要特定类型的所有地址,只需将row_number()切换为dense_rank()

select p.first_name, a.address_1, a.zip, a.state
from person p join
     (select a.*,
             dense_rank() over (partition by a.person_id
                                order by (case when a.address_type = 'T' then 1
                                               when a.address_type = 'M' then 2
                                               when a.address_type = 'R' then 3
                                          end)
                               ) as seqnum
      from addresses a
     ) a
     on p.person_id = a.person_id and seqnum = 1;