【问题标题】:Use NOT IN instead of CTE or temp table使用 NOT IN 代替 CTE 或临时表
【发布时间】:2021-07-05 19:52:36
【问题描述】:
select distinct patientID
from [dbo]..HPrecords 
where ptprocess = 'refill'
and pTDescription <> 'Success'
and patientID is not null
and patiententrytime > '2021-04-06'
and patientID not in (
    select distinct patientID
    from [dbo]..HPrecords 
    where ptprocess = 'embossing'
    and ptDescription = 'Success'
    and patientID is not null
    and patiententrytime > '2021-04-06'
)

所以我想在 SQL 中使用NOT IN 功能来过滤掉尚未收到补充药物的患者。一个病人可以多次补充,第一次可能会失败,但第二次或第三次可能会成功。所以可以有多行。

所以我只想编写一个查询,该查询将过滤掉并让我获得无论多少次都没有成功重新填充的患者 ID。

这是最好的写法吗,我当前的查询还在运行,我觉得逻辑不对?

我想尝试在没有 CTE 或临时表的情况下编写此查询作为练习。

样本输出:

PatientID
151761
151759
151757
151764

【问题讨论】:

  • 1) 请不要到处乱说nolock,除非您非常确定自己需要它并且知道其中的含义。 2) 为什么限制一个可能的解决方案不使用 CTE 或临时表? 3) 提供minimal reproducible example,即样本日期+预期结果。
  • 产生样本输出的样本数据在哪里?
  • Is this the best way to write it 对于NOT IN,没有其他需要更改的地方
  • [dbo]..HPrecords这里多了一个点
  • 解释您的表中的 PatientID 如何可能为 NULL。这似乎不太可能,但您的表名没有提供关于它实际代表什么实体的线索。我还建议您仔细考虑如何编写目标和相关的 sql。病人没有被补充——处方是。有些处方不可补充,有些只能补充。

标签: sql-server optimization common-table-expression temp-tables notin


【解决方案1】:

我个人更喜欢加入而不是加入。看起来更整洁,读起来更好,如果您需要分析异常,则可以访问两张表上的信息。我和一位同事曾经做过一些非常基本的性能比较,没有显着差异。

这是我的看法..

select  distinct hpr.patientID
from    [dbo].HPrecords hpr
        LEFT OUTER JOIN
            [dbo].HPrecords hpr_val ON
                hpr.patientID = hpr_val.patientID
                AND hpr_val.ptprocess = 'embossing'
                AND hpr_val.ptDescription = 'Success'
                and hpr_val.patiententrytime > '20`enter code here`21-04-06'
where   hpr.ptprocess = 'refill'
and     hpr.pTDescription <> 'Success'
--and       hpr.patientID is not null  -- Not necessary because you will always have records in this table in this scenario
and     hpr.patiententrytime > '2021-04-06'
AND     hpr_Val.PatietID IS NULL

在模式和表名之间的额外点上......正如 Smor 指出的那样,它没有必要(甚至可能会破坏查询),而是在您不想在指向数据库时引用模式时使用和桌子。

  • 很长的路要走:[database].[schema].[table] -- 示例 [MyDatabase].[dbo].[MyTable]
  • 快捷方式:[database]..[table] -- 示例 [MyDatabase]..[MyTable]

【讨论】:

    猜你喜欢
    • 2019-03-29
    • 2011-08-24
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 2016-02-11
    • 2014-08-11
    • 1970-01-01
    相关资源
    最近更新 更多