【问题标题】:How to limit my results to only the rows I need?如何将我的结果限制为我需要的行?
【发布时间】:2018-11-23 04:11:11
【问题描述】:

这是我目前拥有的用于提取前 2 个联系人的代码,但是因为当我将 USERID 带入图片时,每家公司都有超过 2 个联系人(这是必需的),它为我提供了包含公司所有用户 ID 的行,尽管他们不是我的前 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 函数吗?

【问题讨论】:

标签: sql sql-server tsql select where


【解决方案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;

【讨论】:

    【解决方案2】:

    我觉得这样更干净

    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
    

    【讨论】:

      猜你喜欢
      • 2017-10-16
      • 2021-10-24
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多