如何计算另一个表中的数据

时间:2014-10-18 10:16:37

标签: mysql count union

我有耐心的病人餐桌 和insurance_cover表有patientnum,insurancecode

我需要展示有保险但无保险,病人数和保险总数的病人, 如果不使用join,我该怎么做?

SELECT 'WITH INSURANCE' AS '',PATIENTNUM, PATIENTSURNAME
from PATIENT where PATIENTNUM 
IN(select PATIENTNUM from INSURANCE_COVER) 

UNION

SELECT 'WITHOUT INSURANCE' AS '',PATIENTNUM, PATIENTSURNAME
from PATIENT where PATIENTNUM 
NOT IN( select PATIENTNUM from INSURANCE_COVER)

此代码显示带有保险但没有保险的数据。 但我不知道如何计算有保险的患者的保险费。

我使用NOT IN是对的吗? 你能帮我吗?

1 个答案:

答案 0 :(得分:0)

SELECT 
    'WITH INSURANCE' AS '',
    PATIENTNUM, 
    PATIENTSURNAME,
    (SELECT COUNT(*) FROM PATIENT tmp WHERE PATIENTNUM IN(select PATIENTNUM from INSURANCE_COVER) AND tmp.PATIENTNUM = p.PATIENTNUM) AS INSURANCES
FROM
    PATIENT p
WHERE 
    PATIENTNUM IN(select PATIENTNUM from INSURANCE_COVER) 

UNION

SELECT 
    'WITHOUT INSURANCE' AS '',
    PATIENTNUM, 
    PATIENTSURNAME,
    0 AS INSURANCES
FROM
    PATIENT 
WHERE
    PATIENTNUM NOT IN( select PATIENTNUM from INSURANCE_COVER)