每个分组的SQL计数

时间:2016-08-01 22:24:03

标签: sql ms-access count

所以我正在为以下内容编写SQL语句。列出每个保险代码的患者数量。

这是我的SQL语句。

SELECT INSURANCE.INS_ID, PATIENT.MPI_LastName
FROM PHYSICIAN 
     INNER JOIN 
           (PATIENT INNER JOIN 
                    (INSURANCE INNER JOIN VISIT 
                       ON INSURANCE.INS_ID = VISIT.VIS_InsuranceCode
                    ) 
             ON PATIENT.MPI_NUMBER = VISIT.VIS_MPINum
           ) 
           ON PHYSICIAN.PHY_ID = VISIT.VIS_Phys
ORDER BY INSURANCE.INS_ID;

我不知道如何编写一个SQL来计算每个保险代码的患者。没有重复记录被计算在内。

I need a count of patients for each code

1 个答案:

答案 0 :(得分:-2)

SELECT INSURANCE.INS_ID, count(distinct PATIENT.MPI_LastName) as count 
  FROM VISIT    
  JOIN PATIENT  
        ON PATIENT.MPI_NUMBER = VISIT.VIS_MPINum
  JOIN INSURANCE 
        ON INSURANCE.INS_ID   = VISIT.VIS_InsuranceCode 
 GROUP BY INSURANCE.INS_ID


  SELECT VISIT.VIS_InsuranceCode, count(distinct PATIENT.MPI_LastName) as count 
  FROM VISIT    
  JOIN PATIENT  
        ON PATIENT.MPI_NUMBER = VISIT.VIS_MPINum
 GROUP BY VISIT.VIS_InsuranceCode