按记录数选择前1名

时间:2018-10-15 15:17:31

标签: sql sql-server tsql

我需要根据归属于每个提供者的索赔数量为每个患者选择最高的提供者,或者换句话说,选择患者最常去的提供者。例如,我有以下数据:

| Patient  | Provider | Claim Number |
| 001      | 001      | 0001         |
| 001      | 002      | 0002         |
| 001      | 002      | 0003         |
| 002      | 001      | 0004         |
| 002      | 003      | 0005         |
| 002      | 003      | 0006         |

所需的结果将显示:

Patient  | Top Provider
001      | 001 
002      | 003

这是我目前的尝试

SELECT pat.patient,clms.provider AS [Top Provider]
FROM PatientList pat
LEFT OUTER JOIN Claims clms
 ON  clms.Provider =(
    SELECT Provider FROM
        (
        SELECT TOP 1 Provider, COUNT(DISTINCT [Claim Number]) 
        FROM Claims
        WHERE ssn = pat.ssn
        GROUP BY Provider
        ORDER BY COUNT(DISTINCT [Claim Number]) desc
        )
    )

2 个答案:

答案 0 :(得分:3)

您需要的是'OUTER APPLY'

我将向您展示总体思路。希望您能对您的数据进行计算。

SELECT pat.patient,clms.provider AS [Top Provider]
FROM PatientList pat

OUTER APPLY (

        SELECT TOP 1 Provider, COUNT(DISTINCT [Claim Number]) 
        FROM CCLF5_PT_B_w_MBI
        WHERE ssn = pat.ssn
        AND
        clms.Provider=pat.Provider
        GROUP BY Provider
        ORDER BY COUNT(DISTINCT [Claim Number]) desc
        )clms

答案 1 :(得分:2)

我会使用row_number()

with cte as (
     <your query goes here>
 )
select Patient, Provider
from (select c.Patient, c.Provider, row_number() over (partition by c.Patient, c.Provider order by count(*) desc) as seq  
      from cte c
      group by Patient, Provider
     ) c
where seq = 1;

我不能接受您目前的尝试。因此,我只是假设使用简单的cte(包含一些JOIN)。