SQL Partitioning,如何在分区组中选择满足一定条件的记录?
Posted
技术标签:
【中文标题】SQL Partitioning,如何在分区组中选择满足一定条件的记录?【英文标题】:SQL Partitioning, how to select a record in the partitioned group that meets certain criteria? 【发布时间】:2020-10-01 19:02:36 【问题描述】:我有一个问题。这个查询是:
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
这就是我想要的。在 partition by 子句中定义的返回的记录组 - 比如说有 3 个返回(行号 1、2、3)。如果其中任何一个的 CaseStatusCode 为“AC”,则从该组中选择该记录。否则,我选择什么记录并不重要。现在,查询只是选择组中的第一条记录 (where Q1.row = 1
)。我很难弄清楚如何做到这一点。有什么想法吗?
【问题讨论】:
【参考方案1】:将该信息放入order by
:
row_number() over (partition by a.Email order by (case when b.CaseStatusCode 'AC' then 1 else 2 end) as row
【讨论】:
以上是关于SQL Partitioning,如何在分区组中选择满足一定条件的记录?的主要内容,如果未能解决你的问题,请参考以下文章
Oracle LiveLabs实验:8 Partitioning Techniques in Oracle Database
Oracle LiveLabs实验:8 Partitioning Techniques in Oracle Database
Oracle LiveLabs实验:8 Partitioning Techniques in Oracle Database
131. Palindrome Partitioning 131.回文分区