Q:

Using rank over partition in MSSQL query

I have a table called relationships_split
 this is the view structure with some data
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:
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
http://sqlfiddle.com/#!6/d36f0/4

A:

Your query is pretty close.  You need a desc on the order by.  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

