首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL查询以获取没有关联服务的用户

SQL查询以获取没有关联服务的用户
EN

Stack Overflow用户
提问于 2020-04-27 19:43:28
回答 2查看 32关注 0票数 0

我把下面的数据放在一个表格里。我试图获取所有的“调制解调器”用户,他们没有相关的电话服务。

代码语言:javascript
复制
UserID   DeviceNumber   DeviceType    DeviceRole
1        A              Telephone     SingleUser
1        A              Modem         MultiUser
1        B              Modem         MultiUser
2        C              Telephone     SingleUser
2        C              Modem         MultiUser
2        D              Modem         MultiUser

select distinct t.* from table t
join table t1 on t1.UserID= v.UserID
and t1.DeviceNumber <> t.DeviceNumber
and t.DeviceType = 'Modem';

我想在输出中看到DeviceNumber B和D。但是上面的查询没有返回预期的结果。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-04-27 19:47:52

嗯嗯。。。一种方法是:

代码语言:javascript
复制
select t.*
from t
where t.devicetype = 'Modem' and
      not exists (select 1
                  from t t2
                  where t2.userid = t.userid and t2.devicenumber = t.devicenumber and
                        t2.devicetype = 'Telephone'
                 );
票数 2
EN

Stack Overflow用户

发布于 2020-04-27 19:48:38

你可以用count来做。这是演示

代码语言:javascript
复制
select
   UserID,
   DeviceNumber,
   DeviceType,
   DeviceRole
from
(
select
    yt.*,
    count(*) over (partition by DeviceNumber) as cnt
from yourTable yt

) val

where cnt = 1
and DeviceType = 'Modem'

输出:

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61467158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档