简体   繁体   中英

SQL Partitioning, how to select a record in the partitioned group that meets certain criteria?

I have a query. This query is:

select Q1.* from (
    select
        a.CreatedDate as KynectCreatedDate,
        a.FirstName,
        b.CaseStatusCode,
        a.Id as ContactId,
        a.Email as EmailAddress,
        a.MobilePhone,
        row_number() over (partition by a.Email order by b.CaseStatusCode desc) as row
    from
        ent.Contact_Salesforce a
    left join
        ent.SOMETABLE_Contact_Shared c on a.Email = c.Email
    left join
        ent.SOMETABLE_Case_Shared b on c.IndividualId = b.IndividualId and c.CaseNumber = b.CaseNumber
    where a.Email = 'aaa@aaa.com') Q1
where Q1.row = 1

Here's what I want. The group of records that come back as defined in the partition by clause - say there's 3 that come back (row number 1, 2, 3). If CaseStatusCode is "AC" on any of them, PICK THAT RECORD OUT OF THE GROUP. Otherwise, DOESN'T MATTER WHAT RECORD I PICK. Right now, the query is just picking the first record in the group ( where Q1.row = 1 ). I'm having a hard time figuring out how to do this. Any ideas?

将该信息按以下order by

    row_number() over (partition by a.Email order by (case when b.CaseStatusCode 'AC' then 1 else 2 end) as row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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