我有一个表FooBaz
,其中包含这样的行(主键是FooId
和baz
的组合):
FooId, Baz, DateTime
1, 2, '2014-05-27 00:01'
2, 2, '2014-05-27 00:01'
3, 2, '2014-05-27 00:01'
1, 3, '2014-05-26 00:01'
2, 4, '2014-05-27 00:01'
3, 5, '2014-05-28 00:01'
我有一个查询,查找Baz == 2
的所有行(除此之外,为了简洁起见,此StackOverflow帖子中未包含这些内容),返回此内容:
FooId, Bar, DateTime
1, 2, '2014-05-27 00:01'
2, 2, '2014-05-27 00:01'
3, 2, '2014-05-27 00:01'
但是,我希望在与另一个FooId
关联时排除与DateTime
相同Baz
时显示的行(在这种情况下,FooId == 3
的最后一行应排除Baz == 5
,因为其DateTime
大于2014-05-27 00:01
。
即。所以最终的结果集应该是这样的:
FooId, Baz, DateTime
1, 2, '2014-05-27 00:01'
2, 2, '2014-05-27 00:01'
请不要告诉我解决方案涉及交叉加入,我不想想:)
答案 0 :(得分:1)
NOT EXISTS
SELECT * FROM FooBaz t1
WHERE Baz = 2
AND NOT EXISTS (
SELECT 1 FROM FooBaz t2
WHERE t2.FooId = t1.FooId
AND t2.DateTime < t1.DateTime
AND t2.Baz <> t1.Baz
)
LEFT JOIN
SELECT t1.FooId, t1.Baz, t1.DateTime
FROM FooBaz t1
LEFT JOIN FooBaz t2 ON t2.FooId = t1.FooId
AND t2.DateTime < t1.DateTime
AND t2.Baz <> t1.Baz
WHERE t1.Baz = 2
AND t2.FooId IS NULL