mysql 我需要此SQL查询问题的解决方案

kg7wmglp  于 2022-10-31  发布在  Mysql
关注(0)|答案(3)|浏览(176)

显示识别为“M”的患者多于识别为“F”的患者的省份。必须仅显示完整的省份名称

**患者表:**患者标识INT名字TEXT姓氏TEXT性别CHAR(1)出生日期DATE城市TEXT省份标识CHAR(2)过敏症TEXT身高INT体重INT
**省份名称表:**省份标识CHAR(2)省份名称TEXT

我试过了,但是没有用。

`select province_name
from patients p,province_names pn
where p.province_id = pn.province_id
and (count(p.province_id) group by p.patient_id having p.gender = 'M' )  >   
(count(p.province_id) group by p.patient_id having p.gender = 'F') `
o2gm4chl

o2gm4chl1#

聚合提供了一种直接的方法:

SELECT pn.province_name
FROM province_names pn
INNER JOIN patients p
    ON p.province_id = pn.province_id
GROUP BY pn.province_name
HAVING COUNT(CASE WHEN p.gender = 'M' THEN 1 END) >
       COUNT(CASE WHEN p.gender = 'F' THEN 1 END);
efzxgjgh

efzxgjgh2#

我认为您的问题已通过此查询解决

select res.province_name

from (SELECT pn.province_name,
             case when p.gender = 'M' then 1 else 0 end as gender_no,
             count(*)                                   as cnt
      FROM province_names pn
               INNER JOIN patients p
                          ON p.province_id = pn.province_id
      group by pn.province_names, p.GENDER) res
where res.gender_no = 1
  and cnt > (select count(*)
             from province_names pnn
                      INNER JOIN patients pp
                                 ON pp.province_id = pnn.province_id
             where res.province_name = pnn.province_name
               and pp.GENDER = 'F');
vnjpjtjt

vnjpjtjt3#

如果您的MySQL版本是8.0.X.X或更高,您可以使用CTE来实现您的目标!!
(Run此命令进行检查:)

mysql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 8.0.28    |
+-----------+
1 row in set (0.00 sec)

完整代码:

WITH CTE AS (SELECT province_name, COUNT(*) AS MaleCount FROM patients p JOIN province_names pn ON p.province_id = pn.province_id WHERE gender = 'M' GROUP BY province_name)
, CTE2 AS (SELECT province_name, COUNT(*) AS FemaleCount FROM patients p JOIN province_names pn ON p.province_id = pn.province_id WHERE gender = 'F' GROUP BY province_name) 
SELECT CTE.province_name FROM CTE JOIN CTE2 ON CTE.province_name = CTE2.province_name WHERE MaleCount > FemaleCount;

相关问题