在MSSQL查询中使用排名超过分区

时间:2014-11-24 17:03:36

标签: sql sql-server common-table-expression window-functions

我有一个名为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')

尝试写一个选择以确保(可能是排名方式) - 我选择了主要关系= 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 个答案:

答案 0 :(得分:1)

您的查询非常接近。您需要desc上的order by。而且,您需要一个子查询来引用该列。

以下内容也清理了一下:

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