MySQL在同一个表上计算子查询

时间:2016-07-27 11:07:11

标签: mysql sql database

我有这个问题:

SELECT `facilities`.`name` AS facility, `countries`.`name` AS country, `states`.`name` AS state, `users`.`dosage` AS dosage, COUNT(`users`.`id`) AS registrations 
FROM `users` 
LEFT JOIN `countries` ON `users`.`country_id` = `countries`.`id` 
LEFT JOIN `states` ON `users`.`state_id` = `states`.`id` LEFT JOIN `user_facilities` ON `users`.`id` = `user_facilities`.`user_id` 
LEFT JOIN `facilities` ON `user_facilities`.`facility_id` = `facilities`.`id` 
WHERE `users`.`dosage` != "Not sure" 
GROUP BY `facilities`.`name`, `countries`.`name`, `states`.`name`, `users`.`dosage` 
ORDER BY `facilities`.`id` ASC, `countries`.`id` ASC, `states`.`name` ASC

它给了我这个结果:

Hospital  | United States | Arkansas | 10 doses  | 3    
Hospital  | United States | Arkansas | >10 doses | 4    
Home care | United States | Arkansas | 10 doses  | 1    
Home care | United States | Texas    | 10 doses  | 1

我的用户表: id |电子邮件| state_id | country_id |剂量| percent_completed

我需要做的是获得每个结果的percent_completed = 100的用户数。我尝试了子查询,但我找不到合适的子查询。我被卡住了。有没有人有一些建议? 感谢。

2 个答案:

答案 0 :(得分:2)

如果我理解正确,您可以使用条件聚合。在MySQL中你可以这样做:

select . . .,
       sum(percent_completed = 100) as num_at_100

答案 1 :(得分:1)

分组后请添加"总和(percent_completed)> = 100"那将是你的用户计算谁完成> = 100%

SELECT `facilities`.`name` AS facility, `countries`.`name` AS country, `states`.`name` AS state, `users`.`dosage` AS dosage, COUNT(`users`.`id`) AS registrations 
FROM `users` 
LEFT JOIN `countries` ON `users`.`country_id` = `countries`.`id` 
LEFT JOIN `states` ON `users`.`state_id` = `states`.`id` LEFT JOIN `user_facilities` ON `users`.`id` = `user_facilities`.`user_id` 
LEFT JOIN `facilities` ON `user_facilities`.`facility_id` = `facilities`.`id` 
WHERE `users`.`dosage` != "Not sure" 
GROUP BY `facilities`.`name`, `countries`.`name`, `states`.`name`, `users`.`dosage` having sum(users.percentage_completed) >= 100
ORDER BY `facilities`.`id` ASC, `countries`.`id` ASC, `states`.`name` ASC