是否可以找到count函数,然后只显示高于10的某些值

hs1rzwqc  于 2021-06-21  发布在  Mysql
关注(0)|答案(4)|浏览(351)

例如:

SELECT doctor.name
     , doctor.surname
     , COUNT(checkup.doctor) 
  FROM doctor
     , checkup 
 WHERE doctor.id = checkup.doctor 
 GROUP 
    BY doctor.name  
 ORDER 
    BY checkup.doctor

这给了我所有的医生,检查过的病人名单,但我想显示只有医生与检查人数超过10个什么添加到我的sql

flvlnr44

flvlnr441#

您希望根据聚合结果限制结果行。你会在晚上做的 HAVING 条款。
至于你的疑问:什么是 name ? 每个医生都有一个独特的名字?否则最好按id分组-只有这样,根据sql标准,此查询才有效。然后您使用的是我们在20世纪90年代停止使用的连接语法。请使用正确的ansi连接。
我更喜欢加入前聚合,但这只是个人喜好:

select d.name, d.surname, c.checkups
from doctor
join 
(
  select doctor as doctor_id, count(*) as checkups
  from checkup 
  group by doctor
  having count(*) > 10
) c on c.doctor_id = d.id
order by d.id;

你也可以用

select d.name, d.surname, count(*) as checkups
from doctor d
join checkup c on c.doctor = d.id
group by d.id
having count(*) > 10
order by d.id;
2lpgd968

2lpgd9682#

试试这个:你可以用 HAVING 子句以筛选出聚合结果并尝试避免过期的联接。 Surname 这并不意味着 GROUP BY 所以你用 MAX 从中选取 GROUP BY 或者保持原样:

SELECT doctor.name
    , doctor.surname
    , COUNT(checkup.doctor) 
FROM doctor
INNER JOIN checkup ON doctor.id = checkup.doctor 
GROUP BY doctor.name, doctor.surname
HAVING COUNT(checkup.doctor) > 10
ej83mcc0

ej83mcc03#

如果只想得到计数超过10的结果(checkup.doctor),请确认使用聚合函数作为计数
您可以使用

SELECT doctor.name,doctor.surname,COUNT(checkup.doctor) 
FROM doctor
INNER JOIN  checkup  doctor.id=checkup.doctor 
GROUP BY doctor.name  
Having  COUNT(checkup.doctor) > 10 
ORDER BY COUNT(checkup.doctor)

where子句作用于选择行,因此不知道聚合结果的结果。。对于这个sql,使用having子句来过滤select的结果

eh57zj3b

eh57zj3b4#

我想这对你有用:

SELECT 
  doctor.name, doctor.surname, checkup_stat.checkup_count 
FROM 
  (SELECT doctor, COUNT(1) AS checkup_count FROM checkup GROUP BY doctor ORDER BY doctor) AS checkup_stat 
RIGHT JOIN 
  doctor 
ON 
  doctor.id = checkup_stat.doctor 
WHERE 
  checkup_stat.checkup_count > 10;

首先,使用子查询获取每个医生的检查计数。
其次,从checkup count>10的子查询结果中选择记录。
然后,把他们连在一起。

相关问题