一种搜索 SQL 以仅提取仅具有空值的数据行的方法

A way to search SQL to only pull rows of data that ONLY HAS null value

这是我的查询:

SELECT patientname, patientID, 
 (CASE WHEN patientID is not null THEN 'yes'
             WHEN CpatientID is null then 'No'    
        END) as submittedintohospital

FROM dbo].[database](nolock)
and patientname = "John Smith"

这是数据结果:

PatientName                     PatientID
John Smith     12345488999       NULL
John Smith     12880889976       NULL

如您所见,一位患者有 2 行结果,我想设置一个条件,其中只有所有行 的patientID为null,则进入case为yes。

因为我编写的当前查询将显示具有空值和非空值的患者​​数据:

例如:

John Wick   1895
John Wick   NULL

我想消除它,只提取患者姓名,其中所有行的患者 ID 都必须为空,而不仅仅是一行。

I want to set a condition where only ALL the rows 's patientID is null, then it will go into case for yes.

您可以使用 window 函数:

select patientname, patientid, 
    case when max(patientid) over(partition by patientname) is null     
        then 'yes'
        else 'no'    
    end as submittedintohospital
from [dbo].[database]

如果您想实际过滤结果:

select patientname, patientid
from (
    select d.*, 
        max(patientid) over(partition by patientname) max_patientid
    from [dbo].[database] d
) d
where max_patientid is null

not exists 也可以方便地进行过滤:

select d.*
from [dbo].[database] d
where not exists (
    select 1 
    from [dbo].[database] d1
    where d1.patientname = d.patientname and d1.patientid is not null
)