【发布时间】: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 函数吗?
【问题讨论】:
-
尝试按
seqnum <= 2过滤 -
*在查询末尾的
WHERE子句中过滤:WHERE seqnum <= 2。复制、粘贴、运行、完成。 -
您有一个不必要的额外子查询。 This should get you there
标签: sql sql-server tsql select where