写入查询的最有效方法是选择null而不是null

时间:2014-04-04 16:07:42

标签: sql-server tsql

我需要选择那些计划编号为null且不为null的患者,这是我的努力:

select distinct PatientID from Visits where plannumber is null and 
patientid = (
select distinct patientid from Visits where plannumber is not 
null group by PatientID) group by PatientID

返回并返回错误'子查询返回的值超过1'。

有没有更有效的方法来编写此查询?

2 个答案:

答案 0 :(得分:0)

select distinct V1.PatientID 
  from Visits V1
  join Visits V2 
    on V2.PatientID = V1.PatientID 
   and V1.plannumber is not null 
   and V2.plannumber is null

select distinct PatientID 
  from Visits 
 where plannumber is not null
INTERSECT 
select distinct PatientID 
  from Visits 
 where plannumber is null

至于您的查询

patientid in 

不是

patientid = 

你的独特和分组是多余的

答案 1 :(得分:-1)

有几种方法,这里有一对......

SELECT
  PatientID
FROM
  Visits
GROUP BY
  PatientID
HAVING
      SUM(CASE WHEN plannumber IS NULL THEN 1 ELSE 0 END) > 0
  AND SUM(CASE WHEN plannumber IS NULL THEN 0 ELSE 1 END) > 0

或者...

SELECT
  *
FROM
  Patient
WHERE
      EXISTS (SELECT * FROM Visits WHERE plannumber IS     NULL AND PatientID = Patient.ID)
  AND EXISTS (SELECT * FROM Visits WHERE plannumber IS NOT NULL AND PatientID = Patient.ID)