【发布时间】:2021-03-03 08:18:28
【问题描述】:
我在附图中有这个数据,有些用户只有药剂师类别,有些用户有医生和药剂师类别,有些用户只有医生类别。 如何获取仅在一行上具有医生类别的用户??
【问题讨论】:
-
这里的大多数人希望样本表数据和预期结果为格式化文本,而不是图像(或图像链接)。
-
还向我们展示您当前的查询尝试。
我在附图中有这个数据,有些用户只有药剂师类别,有些用户有医生和药剂师类别,有些用户只有医生类别。 如何获取仅在一行上具有医生类别的用户??
【问题讨论】:
您可以检查是否存在医生以外的状态。
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')
顺便说一句,在医生类别中包含类别真的有用吗?
【讨论】:
您可以使用以下查询完成它:
架构 (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 |
【讨论】:
您可以检查使用存在关键字,所有您需要使用医生类别搜索数据和任何其他类别的不存在子句。
如下所示
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');
【讨论】: