[英]Using rank over partition in MSSQL query
我有一个名为Relationships_split的表,这是带有一些数据的视图结构
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')
试图写一个选择来确保(可能以等级的方式)-我选择的是primaryrelationship = 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小提琴上
您的查询非常接近。 您需要按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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.