【问题标题】:Get users based on status根据状态获取用户
【发布时间】:2021-03-03 08:18:28
【问题描述】:

我在附图中有这个数据,有些用户只有药剂师类别,有些用户有医生和药剂师类别,有些用户只有医生类别。 如何获取仅在一行上具有医生类别的用户??

【问题讨论】:

  • 这里的大多数人希望样本表数据和预期结果为格式化文本,而不是图像(或图像链接)。
  • 还向我们展示您当前的查询尝试。

标签: mysql sql database


【解决方案1】:

您可以检查是否存在医生以外的状态。

select distinct tw_userid
from users
where not exists(select 1 from users t1 where t1.tw_userid = t.tw_userid and category_status <> 'Doctor Category')

顺便说一句,在医生类别中包含类别真的有用吗?

【讨论】:

    【解决方案2】:

    您可以使用以下查询完成它:

    架构 (MySQL v5.7)

    create table users(
       tw_userId INT ,
       category_Status VARCHAR(100) NOT NULL
    );
    
    insert into users
    values
    (8,'Doctor Category'),
    (8,'Doctor Category'),
    (8,'Doctor Category'),
    (2836,'pharmacist Category'),
    (2836,'pharmacist Category'),
    (13174,'Doctor Category');
    

    查询 #1

    SELECT tw_userId, COUNT(*) as total
    , COUNT(CASE WHEN category_status = 'Doctor Category' THEN 1 END) as doctor_total FROM users
    group by tw_userId 
    HAVING total = doctor_total;
    
    tw_userId total doctor_total
    8 3 3
    13174 1 1

    View on DB Fiddle

    【讨论】:

    • DBfiddle 是空的?
    • and total = 1 - excludes userid = 8 OP 已勾选,因此应包括在内
    • @P.Salmon,抱歉之前没有注意到。谢谢。我已经更新了我的答案。
    【解决方案3】:

    您可以检查使用存在关键字,所有您需要使用医生类别搜索数据和任何其他类别的不存在子句。

    如下所示

    select * from users u1 where category_status = 'Doctor_Category'
    and not exists (select 1 from users u2 where u1.tw_userid = u2.tw_userid and category_status<> 'Doctor_category');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-15
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多