根据表中的其他行排除行

时间:2014-05-27 21:52:21

标签: sql

我有一个表FooBaz,其中包含这样的行(主键是FooIdbaz的组合):

 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'

请不要告诉我解决方案涉及交叉加入,我不想想:)

1 个答案:

答案 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