我已经尝试了2个多小时,但是根本无法解决。

我有2个表-带“ PatientNum”列的“患者”和带“ insuranceCode”,“ PatientNum”列的“ insurance_cover”。

我想显示所有有保险的患者,以及他们的患者人数和所覆盖的不同保险公司的数量(这是我一直遇到的问题)。

这就是我想要的输出,因为解释可能会令人困惑

  Insurance Cover | Patient Number | Number of insurances
    -------------------------------------------------------
    With Insurance| 1              | 3
    With Insurance| 2              | 1
    With Insurance| 3              | 1
    No Insurance  | 4              | N/A
    No Insurance  | 5              | N/A


我也意识到我需要使用UNION,但是我尚未能够使第一部分正常工作,所以还没有尝试过

这是我目前的尝试

SELECT  CONCAT('With Insurance ', pat.`PatientNum`)
                          AS `Insurance cover + Patient Number`,
        CONCAT(pat.`PatientFirstname`, ' ', pat.`PatientSurname`)
                          AS `Patient Name`,
        COUNT(`patientNum`) GROUP BY `patientNum`
  FROM  `patient` AS pat,
        `insurance_cover` AS ins
 WHERE ins.`PatientNum` = pat.`PatientNum`
   AND ins.PatientNum IN (SELECT ins.`PatientNum`
                            FROM `insurance_cover`)
 GROUP BY pat.`PatientNum`;


任何帮助表示赞赏

要求的表定义位于http://imgur.com/a/7k22r(我不能插入低重复数的图片)

最佳答案

您应该使用类似以下的查询:

SELECT patientNum,
       number_of_insurances,
       (CASE number_of_insurances WHEN 0 THEN 'Not covered' ELSE 'Covered' END)
  FROM (
      SELECT patient.patientNum,
             count(*) as number_of_insurances,
        FROM patient
   LEFT JOIN insurance_cover ON patient.patientNum = insurance_cover.patientNum
   GROUP BY patient.patientNum
      ) AS S


编辑:根据下面的注释,您不能使用JOIN。因此,这是另一个(效率较低)的答案:

SELECT (CASE (SELECT COUNT(*)
                FROM insurance_cover AS i1
               WHERE i1.patientNum = p.patientNum
             )
        WHEN 0 THEN 'Not covered'
        ELSE 'Covered'
        END) AS covered,
       p.patientNum,
       (SELECT COUNT(*)
          FROM insurance_cover AS i2
         WHERE i2.patientNum = p.patientNum
       ) AS number_of_insurances
  FROM patient p

关于mysql - 显示所有有保险但无保险的患者,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26481223/

10-09 06:05