每月查找具有最大唯一患者数的前 2 个帐户

Find the top 2 accounts with the maximum number of unique patients on a monthly basis

找到每月唯一患者数量最多的前 2 个帐户 基础。 患者记录 table

Account Id | date | Patient Id
1 2-1-2020 100
1 27-1-2020 200
2 1-1-2020 300
2 21-1-2020 400
2 21-1-2020 300
2 1-1-2020 500
3 20-1-2020 400
1 4-3-2020 500

示例输出

Month |Account ID | no of unique patients
January 2 3
January 1 2
March 3 1

*注意:在相同数量的唯一患者的情况下,优先选择具有最小值的帐户 ID

这是一种方法:

select * from (
   select * , row_number() over (partition by month,AccountID order by count(distinct patienId) desc) rn
)  t
where t.rn < 3

您可以使用 window 函数和聚合:

select aym.*
from (select accountId, year(date) as yyyy, month(date) as mm,
             count(distinct patient_id) as num_patients,
             row_number() over (partition by year(date), month(date) order by count(distinct patient_id) as seqnum
      from t
      group by accountId, year(date), month(date)
     ) aym
where seqnum <= 2;

日期函数因数据库而异。 YEAR()MONTH() 是常用函数;如果您的数据库不支持它们,您应该能够找到合适的函数。