简体   繁体   English

根据不同条件选择行

[英]Select row depending upon different condition

My source table looks something like below 我的源表如下所示 在此处输入图片说明

This is the intermediate step 这是中间步骤 在此处输入图片说明

And the final output should look like below 最终输出应如下所示 在此处输入图片说明

Basically first I need to SELECT the lowest Rank for a PERSONID , AddressID and PhoneType . 基本上,首先我需要为PERSONIDAddressIDPhoneType SELECT最低的Rank If there are multiple rows with the same Rank , then I need to return which ever has the max VerificationDate and then get the final output. 如果有多个具有相同Rank行,那么我需要返回具有最大VerificationDate ,然后获得最终输出。

Create statement: 创建语句:

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];

Try this query: 试试这个查询:

Sample data ( not the same, but it is equivalent ): 样本数据( 不相同,但等效 ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM