不知道有人会知道怎么做吗?
基本上我只需要返回Type等于'I'的结果,所以我删除了行---- AND PatientType ='I'----这就像一个魅力,但后来我发现我有一些具有相同MRN的记录包含两种类型的“I”和“O”。如果它们有“O”,那么我就不能计算它们的“我”。现在这意味着我必须删除满足该条件的那些是的,你猜对了我再次陷入困境.LOL
SELECT DISTINCT
p.id,
v.PatientID,
p.firstname,
p.lastname,
p.dob,
p.mrn,
s.SmokeStatus,
v.VisitNo,
s.VisitID,
v.ID,
v.AdmitedDate
FROM
tblPatient p
JOIN tblPatientVisit v ON p.id = v.PatientID
JOIN tblPatientSmokingScreenOrder s ON v.id = s.VisitID
WHERE
isdate(p.DOB) = 1
AND CONVERT(date,p.DOB) <'12/10/2000'
AND isdate(v.AdmitedDate) = 1
AND CONVERT(date,v.AdmitedDate) > '06/16/2013 00:00'
AND v.PatientType = 'I'
AND s.TobaccoType = 'Cigarettes' OR s.TobaccoType='Cigars' or s.TobaccoType='Pipes'
AND v.PatientType !='O'
AND v.PatientType !='2'
AND v.PatientType = 'I'
order by MRN
答案 0 :(得分:2)
添加括号,因为OR和AND之间存在运算符优先级问题。
AND (s.TobaccoType = 'Cigarettes' OR s.TobaccoType='Cigars' or s.TobaccoType='Pipes')
或更好,IN
条款
AND s.TobaccoType IN ('Cigarettes', 'Cigars', 'Pipes')
然后,添加一个NOT EXISTS
条款(如果我理解的话),以排除患者“任何访问中的O”
AND NOT EXISTS (select null from
tblPatientVisit
where PatientId = p.id
and PatientType = 'O')
所以整个查询应该是(不确定v.PatientType != '2'
应该去哪里)
SELECT DISTINCT
p.id,
v.PatientID,
p.firstname,
p.lastname,
p.dob,
p.mrn,
s.SmokeStatus,
v.VisitNo,
s.VisitID,
v.ID,
v.AdmitedDate
FROM
tblPatient p
JOIN tblPatientVisit v ON p.id = v.PatientID
JOIN tblPatientSmokingScreenOrder s ON v.id = s.VisitID
WHERE
isdate(p.DOB) = 1
AND CONVERT(date,p.DOB) <'12/10/2000'
AND isdate(v.AdmitedDate) = 1
AND CONVERT(date,v.AdmitedDate) > '06/16/2013 00:00'
AND v.PatientType = 'I'
AND v.PatientType !='2'
AND s.TobaccoType IN ('Cigarettes', 'Cigars', 'Pipes')
AND NOT EXISTS (select null from
tblPatientVisit
where PatientId = p.id
and PatientType = 'O')