在 MSSQL 查询中使用分区排名
Posted
技术标签:
【中文标题】在 MSSQL 查询中使用分区排名【英文标题】:Using rank over partition in MSSQL query 【发布时间】:2014-11-24 17:03:36 【问题描述】:我有一个名为关系分割的表 这是带有一些数据的视图结构
create table relationships_split
(rel id int ,
rel_type_id varchar (20),
rel_type_group_id varchar(20),
rel_type_class_id varchar(20),
contact_id int,
isprimaryrelationship int,
dtadded datetime,
dtmodified datetime,
opposite_contact_id int)
insert into relationships_split
(rel_id,rel_type_id,rel_type_group_id,rel_type_class_id,contact_id,isprimaryrelationship,dtadded,dtmodified,opposite_contact_id)
VALUES
(29715, 2, 1, 2, 2138306, 0, '2012-10-26 11:08:55.230', '2012-10-26 11:08:55.230', 2138153),
(29715, 2, 1, 2, 2138306, 0, '2012-10-26 11:08:55.230', '2012-10-26 11:08:55.230', 2138153),
(29715, 2, 1, 2, 2138306, 0, '2012-10-26 11:08:55.230', '2012-10-26 11:08:55.230', 2138153),
(47574, 2, 1, 2, 1719969, 1, '2012-12-27 17:12:46.980', '2012-12-27 17:12:46.980', 1710276),
(47574, 2, 1, 2, 1719969, 1, '2012-12-27 17:12:46.980', '2012-12-27 17:12:46.980', 1710276),
(47574, 2, 1, 2, 1719969, 1, '2012-12-27 17:12:46.980', '2012-12-27 17:12:46.980', 1710276),
(47574, 2, 1, 2, 1719969, 1, '2012-12-27 17:12:46.980', '2012-12-27 17:12:46.980', 1710276)
create table contacts
(id int,
fullname varchar (900)
)
insert into contacts
(id,fullname)
values
(1719969,'Carrie Smith'),
(2138306,'Stephen Rosenthal')
尝试编写一个选择以确保(可能以排名方式) - 我选择主要关系 = 1 只是这就是我所拥有的,我认为它非常错误:
with ids as (select id from contacts)
select
z.contact_id ,z.rel_id,
rank() over(partition by z.rel_id order by case when isprimarrelationship =1 then 1 else 0 end) as r
from
relationships_split z inner join ids
on z.contact_id = z.id
where r = 1
也在 SQL Fiddle 上
http://sqlfiddle.com/#!6/d36f0/4
【问题讨论】:
【参考方案1】:您的查询非常接近。您需要order by
上的desc
。而且,您需要一个子查询来引用该列。
以下内容也稍微清理了一下:
select rs.contact_id, rel_id
from (select rs.contact_id, rs.rel_id,
rank() over (partition by rs.rel_id
order by (case when isprimaryrelationship =1 then 1 else 0 end) desc
) as seqnum
from relationships_split rs
) rs
where seqnum = 1
【讨论】:
以上是关于在 MSSQL 查询中使用分区排名的主要内容,如果未能解决你的问题,请参考以下文章
无法使用 pypyodbc 在 python 中使用 where 子句运行 mssql 选择查询