我试图找到患者who are active on date 2016-05-01 but not active on date 2016-06-01
,患者Z673032
。见下表
pat_id dm_date
-------------------------------
Z672385 2016-05-01 00:00:00.000
Z672385 2016-06-01 00:00:00.000
Z672444 2016-05-01 00:00:00.000
Z672444 2016-06-01 00:00:00.000
Z672570 2016-05-01 00:00:00.000
Z672570 2016-06-01 00:00:00.000
Z672995 2016-05-01 00:00:00.000
Z672995 2016-06-01 00:00:00.000
Z673032 2016-05-01 00:00:00.000
我的查询:
select A.pat_id
from A
where
A.dm_date = '2016-05-01'
and A.PAT_ID not in (select B.pat_id
from B
where B.dm_date = '2016-06-01')
但它返回Null。它应该是直截了当的但是......对此有何看法? 我使用的是SQL Server Management Studio。
答案 0 :(得分:1)
您需要在别名之前包含表名。
检查 demo fiddle
select A.pat_id
from Table1 A
where
A.dm_date = '2016-05-01'
and A.PAT_ID not in (select B.pat_id
from Table1 B
where B.dm_date = '2016-06-01')
答案 1 :(得分:0)
尝试将表格加入到自己中
SELECT a.pat_id
FROM a
LEFT JOIN b
ON a.pat_id = b.pat_id
WHERE a.dm_date BETWEEN '2016-05-01 00:00:00' AND '2016-05-01 23:59:59'
AND b.pat_date BETWEEN '2016-06-01 00:00:00' AND '2016-06-01 23:59:59'
在比较日期时间戳时,SQL Server可能会对如何解释日期感到挑剔。