按ID(非主键)分组,具有多种类型的地址

时间:2012-12-20 21:21:39

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

我的地址表如下所示:

AddressID Street        City         AddressTypeID    PersonID
1         1st 2ave      Edmonton     1                10
2         3st 6ave      Edmonton     2                10
3         8st 5ave      Edmonton     5                10
4         7st 4ave      Edmonton     2                11
5         2st 9ave      Edmonton     3                12
6         9st 2ave      Edmonton     5                12

在该表中,personid 10具有3种不同类型的地址。 我想结果是group by personID,其优先级为addressTypeID 1,如果该人没有addresstypeID 1则使用addresstypeID 5

我希望输出看起来像这样:

AddressID Street        City         AddressTypeID    PersonID
1         1st 2ave      Edmonton     1                10
4         7st 4ave      Edmonton     2                11
6         9st 2ave      Edmonton     5                12

感谢您回答我的问题

4 个答案:

答案 0 :(得分:4)

; with cte as (
    select 
        a.AddressID, a.Street, a.City, a.AddressTypeID, a.PersonID,
        row_number() over(
            partition by a.PersonID 
            order by case a.AddressTypeID
                when 1 then 1
                when 5 then 2
                else 3
            end
        ) as rn
    from address a
)
select *
from cte
where rn = 1

答案 1 :(得分:1)

这样的东西
SELECT AddressTable.* FROM AddressTable INNER JOIN 

(SELECT PersonID, MIN(AddressID) as MinAddressID GROUP BY PersonID) AS MinIdTable ON 

AddressTable.AddressID = MinIdTable.MinIdTable

答案 2 :(得分:1)

这不是一个小组,而是使用row_number()函数:

select a.*
from (select a.*,
             row_number() over (partition by personId
                                order by (case when AddressTypeId = 1 then 1
                                               when AddressTYpeId = 5 then 2
                                               else 3
                                          end)
                               ) as seqnum
      from addresses a
     ) a
where seqnum = 1

请注意,我在case子句中使用order by语句来指定您的优先级。

答案 3 :(得分:0)

首先,通过子查询过滤表,使其仅包含AddressTypeID为1或5的行。然后选择具有最低AddressTypeID的每个人一个(因为您希望1优先于5)

select 
    *
from
    (select * from myaddresstable 
    where AddressTypeID in (1, 5))
where
    row_number() over (partition by PersonID order by AddressTypeID asc) = 1