根据不同条件选择行

时间:2018-08-10 14:56:06

标签: sql sql-server

我的源表如下所示 enter image description here

这是中间步骤 enter image description here

最终输出应如下所示 enter image description here

基本上,首先我需要SELECT RankPERSONIDAddressID的最低PhoneType。如果有多行具有相同的Rank,那么我需要返回最大VerificationDate的行,然后获得最终输出。

创建语句:

CREATE TABLE AddressPhone ([PERSONID] [varchar](10) NOT NULL,
                           [AddressID] [int] NOT NULL,
                           [PhoneType] [varchar](2) NOT NULL,
                           [PhoneNumber] [varchar](15) NOT NULL,
                           [VerificationDate] [datetime] NOT NULL,
                           [Rank] [int] NOT NULL) ON [PRIMARY];

1 个答案:

答案 0 :(得分:1)

尝试此查询:

样本数据(不相同,但等效):

declare @tbl table (personid int, addressid int, phonetype bit, phonenumber int, verificationdate date, rank int);
insert into @tbl values
(1, 1, 0, null, '2014-06-24', 4),
(1, 1, 1, null, '2014-06-24', 4),
(1, 1, 1, null, '2014-06-24', 4),
(1, 1, 1, null, '2014-06-24', 4),
(1, 1, 1, null, '2014-06-24', 4),
(1, 1, 0, null, '2014-06-24', 4),
(1, 1, 0, null, '2014-06-24', 3),
(1, 1, 0, null, '2014-06-24', 4),
(1, 1, 1, null, '2014-06-24', 2),
(1, 1, 1, null, '2014-06-24', 1),
(1, 1, 0, null, '2014-06-24', 4),
(1, 1, 1, null, '2014-06-24', 4),

(2, 2, 0, null, '2014-06-24', 2),
(2, 2, 0, null, '2014-06-24', 1),
(2, 2, 0, null, '2014-06-24', 4),
(2, 2, 1, null, '2014-06-25', 1),
(2, 2, 1, null, '2014-06-24', 1);

--intermediate step
select personid, addressid, phonetype, phonenumber, verificationdate, rank,
       row_number() over (partition by rank order by verificationdate) rnVerDate
from (
    select personid, addressid, phonetype, phonenumber, verificationdate, rank,
           row_number() over (partition by personid, addressid, phonetype order by rank desc) rnRank
    from @tbl
) a where rnRank = 1

--final result
select personid, addressid, phonetype, phonenumber, verificationdate, rank
from (
    select personid, addressid, phonetype, phonenumber, verificationdate, rank,
           row_number() over (partition by rank order by verificationdate) rnVerDate
    from (
        select personid, addressid, phonetype, phonenumber, verificationdate, rank,
               row_number() over (partition by personid, addressid, phonetype order by rank desc) rnRank
        from @tbl
    ) a where rnRank = 1
) a where rnVerDate = 1