向所有患者展示保险和无保险

时间:2014-10-21 07:33:07

标签: mysql

我一直试图这样做超过2个小时,但根本无法理解。

我有2个表 - '患者'有'PatientNum'列,'insurance_cover'有'insuranceCode','patientNum'列。

我想向所有患者展示保险,他们的患者人数以及他们所涵盖的不同保险公司的数量(这是我遇到麻烦的部分)。

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

  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(我无法插入低代表的图片)

1 个答案:

答案 0 :(得分:1)

您应该使用如下查询:

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