代码之家  ›  专栏  ›  技术社区  ›  sqlrobert

SQL-如何查找不包含特定字段值的一组记录

  •  0
  • sqlrobert  · 技术社区  · 1 年前

    我正在处理医疗索赔数据,我需要帮助来证明一个假设。

    我想找到没有适当诊断代码的特定药物的所有索赔。

    所以,假设我有Drug-X,只有在诊断代码为H99的情况下才能计费(在下面的权利要求123中,因为它有正确的代码,所以它是有效的),我想找到使用Drug-X计费但根本没有诊断代码H99的索赔。

    此外,ICD10代码可以附加到该索赔的服务(或所有服务)的任何行

    在下面的示例中:我希望能够仅返回索赔ID为321的记录

    索赔ID 个人ID 服务 ICD10代码
    123 555 注射 H99
    123 555 药物-X
    123 555 考试
    123 555 诊断
    321 556 注射 小时88
    321 556 药物-X
    321 556 考试
    321 556 诊断

    我已经尝试使用一些where in(选择不同的索赔ID)和 Exists 功能,但它们似乎不起作用。

    1 回复  |  直到 1 年前
        1
  •  1
  •   SelVazi    1 年前

    这可以使用 group by having 子句,条件是使Claims至少有一个 药物-X 而没有 H99 代码:

    select t.*
    from mytable t
    inner join (
      select Claim_ID
      from mytable
      group by Claim_ID
      having count(case when Service = 'Drug-X' then 1 end) > 0
             and count(case when ICD10_Code = 'H99' then 1 end) = 0 
    ) as s on s.Claim_ID = t.Claim_ID
    

    Demo here

        2
  •  0
  •   Charlieface    1 年前

    使用窗口函数而不是自联接可能更有效。

    select t.*
    from (
        select *,
          count_DrugX = count(case when Service = 'Drug-X' then 1 end) over (partition by Claim_ID),
          count_H99   = count(case when ICD10_Code = 'H99' then 1 end) over (partition by Claim_ID)
        from mytable t
    ) t
    where count_DrugX > 0
      and count_H99 = 0;
    
        3
  •  0
  •   Ben Thul    1 年前

    以下是一个使用 exists :

    with yourData as (
        select *
        from (values
            ('123', '555', 'Injection', 'H99'),
            ('123', '555', 'Drug-X', NULL),
            ('123', '555', 'Exam',NULL),
            ('123', '555', 'Diagnosis', NULL),
            ('321', '556', 'Injection', 'H88'),
            ('321', '556', 'Drug-X', NULL),
            ('321', '556', 'Exam',  NULL),
            ('321', '556', 'Diagnosis',  NULL)
        ) as x(ClaimID, PersonID, [Service], [IDC10])
    ), badClaims as (
        select ClaimID
        from yourData
        where [Service] = 'Drug-X'
            and not exists (
                select *
                from yourData as t
                where yourData.ClaimID = t.ClaimID
                    and IDC10 = 'H99'
            )
    )
    select *
    from yourData
    join badClaims
        on badClaims.ClaimID = yourData.ClaimID;
    

    对其进行细分,cte-badClaims查找具有Drug-X的行项目,并且同一索赔中没有IDC10=H99的行项目。一旦找到此类索赔,我们将返回该索赔的所有行项目。