【问题标题】:Query returns duplicate records due to multiple values in a column for same record. Need help to filter the query由于同一记录的列中有多个值,查询返回重复记录。需要帮助过滤查询
【发布时间】:2019-06-02 22:00:00
【问题描述】:

我有一个包含多个种族代码值的客户记录。每个种族代码都有一个在查找表中定义的优先级编号。我当前的选择查询为给定客户的每个种族值创建了一条记录。我想使用优先级值并仅检索具有最高优先级值的客户的记录。 (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

我目前的结果集如下

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

【问题讨论】:

  • 同一个id的三列值存在差异。您希望如何合并它们?
  • 你能展示三个表的结构吗?请注意,您可以创建一个不同的 external_id,但如果您有与此字段相关的其他值,您的查询实际上会重复出现。

标签: sql-server tsql


【解决方案1】:

您可以使用row_number() 实现它,它将为每个patient_id 分配1 (numberPriority),highest prioritypatient_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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多