由于同一记录的列中有多个值,因此查询返回重复的记录。需要帮助来过滤查询

时间:2019-06-02 13:31:02

标签: sql-server tsql

我有一个具有多个种族代码值的客户记录。每个种族代码都有一个优先级编号,该编号在查找表中定义。我当前的选择查询为给定客户的每个种族值创建一条记录。我想使用优先级值,并且只检索具有最高优先级值的客户的记录。 (最高优先级为1,最低优先级为99)

我的选择查询当前正在为客户返回每个种族代码的记录。

select distinct external_id,
pat.patient_id,
eth.ethnicity_code,
et.description,
et.priority
FROM
patient.patient pat
INNER JOIN patient.Ethnicity eth ON pat.patient_id=eth.patient_id
INNER JOIN lookup.LK_EthnicityCode et ON eth.ethnicity_code=et.ethnicity_code

我当前的结果集如下

Actual Result

我的预期结果应该只包含上述结果集中的第1,2,3,4,7和8行。

2 个答案:

答案 0 :(得分:0)

您可以使用row_number()实现它,它将为numberPriority中的patient_id分配给每个highest priority 1(patient_id)(1最高,最低优先级为99。

with patients as  (
    select distinct external_id,
    pat.patient_id,
    eth.ethnicity_code,
    et.description,
    et.priority,
    row_number() over (partition by pat.patient_id order by et.priority asc) as numberPriority
    FROM
    patient.patient pat
    INNER JOIN patient.Ethnicity eth ON pat.patient_id=eth.patient_id
    INNER JOIN lookup.LK_EthnicityCode et ON eth.ethnicity_code=et.ethnicity_code
)
select  
    *
from patients
where numberPriority = 1

答案 1 :(得分:0)

我也在玩我的查询,并通过对原始查询进行以下修改获得了预期的结果

select distinct external_id,
pat.patient_id,
eth.ethnicity_code,
et.description,
et.priority
FROM
patient.patient pat
INNER JOIN patient.Ethnicity eth ON pat.patient_id=eth.patient_id
INNER JOIN lookup.LK_EthnicityCode et ON eth.ethnicity_code=et.ethnicity_code
And et.priority = ( SELECT min(et1.priority) 
FROM lookup.LK_EthnicityCode et1, patient.Ethnicity eth1
where eth1.ethnicity_code=et1.ethnicity_code
and eth.patient_id=eth1.patient_id )
ORDER BY patient_id