如何在子查询中添加Count

时间:2017-03-22 13:03:49

标签: sql sql-server-2008

我必须在子查询中计算。我想将其添加到子查询中。 将此行添加到子查询时,我收到了失败:    SELECT COUNT(DISTINCT v.Department_descr),v.Patient_Number,b.patient_name FROM vwGenVouchInfo v)as pat_dept

SELECT *
FROM vwGenVouchInfo v
WHERE v.Patient_Number=b.Patient_Number
  AND v.Voucher_Primary_Diagnosis_Code  IN ('Z00.129', 'Z00.00') )
ORDER BY voucher_primary_diagnosis_code

我希望得到一个结果,让病人最常去哪个部门。我不知道如何添加它。我希望pat_dept能够让患者除了牙科以外的大部分时间进行治疗。

SELECT distinct
    a.voucher_primary_diagnosis_code,
   a.Patient_Number
,   b.Patient_Name, b.patient_home_phone, patient_age
FROM vwGenVouchInfo a 
LEFT JOIN vwGenPatInfo b ON a.Patient_Number=b.Patient_Number
WHERE
    a.Department_Descr = 'Dental'
and a.Voucher_Service_Date >= '2015-01-01'
AND NOT EXISTS (
    -- This subquery looks at other vouchers of the same patient.

    -- 
    SELECT *
    FROM vwGenVouchInfo v
    WHERE v.Patient_Number=b.Patient_Number
      AND v.Voucher_Primary_Diagnosis_Code  IN ('Z00.129', 'Z00.00') )
ORDER BY voucher_primary_diagnosis_code

1 个答案:

答案 0 :(得分:0)

如果您需要在子查询中使用此选项,则必须将所有必需的列与计数一起放在一起,然后按相同的列进行分组。