1

我的地址表如下所示:

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 种不同类型的地址。我希望结果是按优先级为 addressTypeID 1 的 personID 分组,如果此人没有 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

4 回答 4

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
于 2012-12-20T21:27:17.997 回答
1

就像是

SELECT AddressTable.* FROM AddressTable INNER JOIN 

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

AddressTable.AddressID = MinIdTable.MinIdTable
于 2012-12-20T21:27:19.017 回答
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来指定您的优先级。

于 2012-12-20T21:28:53.857 回答
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
于 2012-12-20T21:31:27.720 回答