如何将我的结果限制为只需要我需要的行?

时间:2018-06-13 14:20:08

标签: sql sql-server tsql select where

这是我目前提供前2个联系人的代码,但因为当我将USERID引入图片(这是必需的)时,每个公司都有超过2个联系人,它为我提供了包含公司所有Userids的行,尽管他们不是我的前2个联系人。

select companyid, 
 userid,
(case when seqnum = 1 then username end) as  Contact1,
(case when seqnum = 2 then username end) as  Contact2,


from (
select *, row_number() over (partition by companyid order by username) as 
seqnum from 
( SELECT b.userid, username, a.companyid from [UsersInCompanies] a
JOIN [Companies] c on a.companyid = c.companyid 
join [aspnet_Users] b on a.userid = b.userid ) t ) l

结果集我正在

CompanyID Userid  Contact1  Contact2 
1         xyz-78  Jane Doe1  NULL    
1         uik-90  NULL       JD2    
1         jkl-70  NULL       NULL
1         abc-60  NULL       NULL

期望的结果

CompanyID Userid  Contact1  Contact2 
1         xyz-78  JaneDoe1  NULL    
1         uik-90  NULL       JaneDoe2    

我应该使用某种COUNT& TOP功能?

2 个答案:

答案 0 :(得分:1)

您需要过滤(即seqnum <= 2),但我会将其重写为:

with t as (
        SELECT b.userid, username, a.companyid, 
               ROW_NUMBER() OVER (PARTITION BY a.companyid order by b.username) as seqnum 
        FROM [UsersInCompanies] a INNER JOIN 
             [Companies] c 
             ON a.companyid = c.companyid INNER JOIN 
             [aspnet_Users] b 
             ON a.userid = b.userid
 )
select companyid, userid,
       (case when seqnum = 1 then username end) as  Contact1,
       (case when seqnum = 2 then username end) as  Contact2
from t
where seqnum <= 2;

答案 1 :(得分:1)

我认为这更清洁

with cte as 
(
    SELECT b.userid, username, a.companyid, 
           ROW_NUMBER() OVER (PARTITION BY a.companyid order by b.username) as rn 
    FROM [UsersInCompanies] a 
    JOIN [Companies] c 
      ON a.companyid = c.companyid 
    JOIN [aspnet_Users] b 
      ON a.userid = b.userid
)
select ct1.*, cte2.username 
  from cte as cte1 
  join cte as cte2 
    on cte1.companyid = cte2.companyid
   and cte1.rn = 1
   and cte2.rn = 2