简体   繁体   English

在MSSQL查询中使用分区之上的排名

[英]Using rank over partition in MSSQL query

I have a table called relationships_split this is the view structure with some data 我有一个名为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')

Trying to write a select to make sure (in possibly a rank fashion) - I am selecting the primaryrelationship = 1 only this is what i have and i think its pretty wrong: 试图写一个选择来确保(可能以等级的方式)-我选择的是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

Also on SQL Fiddle 同样在SQL小提琴上

http://sqlfiddle.com/#!6/d36f0/4 http://sqlfiddle.com/#!6/d36f0/4

Your query is pretty close. 您的查询非常接近。 You need a desc on the order by . 您需要按order bydesc And, you need a subquery to refer to the column. 并且,您需要一个子查询来引用该列。

The following also cleans it up a bit: 以下内容也将其清理干净:

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.

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