我有一张这样的表:
LocationId | CreatedDate | HeadCount
-----------+-------------+-----------
1 | 2017-6-5 | 12
3 | 2017-6-5 | 458
5 | 2017-6-5 | 125
1 | 2017-8-5 | 12
5 | 2017-8-5 | 458
我需要找到表中存在于特定日期但在另一个日期不存在的所有LocationIds。因此,在上表中,我需要返回
3 | 2017-6-5 | 458
我正在尝试以下方法,但我想我可能需要使用临时表来完成我的任务。
SELECT *
FROM HeadCounts a
FULL OUTER JOIN HeadCounts b ON a.LocationId = b.LocationId
WHERE a.CreatedDate = '2017-6-5'
AND b.CreatedDate = '2017-6-5'
AND a.LocationId IS NULL
OR b.LocationId IS NULL
非常感谢任何帮助。
答案 0 :(得分:2)
您可以使用WHERE NOT EXISTS
:
Select *
From HeadCounts H1
Where Not Exists
(
Select *
From HeadCounts H2
Where H1.LocationId = H2.LocationId
And H1.CreatedDate <> H2.CreatedDate
)
答案 1 :(得分:1)
由于您只需要这两个特定日期,因此可以执行此类操作。
select LocationID
, MAX(CreatedDate)
, MAX(HeadCount)
from YourTable
where CreatedDate in ('2017-6-5', '2017-8-5')
group by LocationID
having count(*) <= 1
答案 2 :(得分:0)
select LocationId, CreatedDate, HeadCount
from HeadCounts
where LocationId not in(
select LocationId from HeadCounts
where locationid in(
select LocationId from HeadCounts
where CreatedDate = '2017-6-5')
and CreatedDate != '2017-6-5')