Select 在特定列中包含所有指定值的所有组

Select all groups that contain all specified values in a certain column

假设我有以下 table:

CaseRef NotificationReason NotificationDate
123 SCHEDULED 2022-01-01
234 SCHEDULED 2022-01-02
312 SCHEDULED 2022-01-01
123 RESCHEDULED 2022-01-02
123 DECIDED 2022-01-03
234 DECIDED 2022-01-02

如果我只想 return 具有 CaseRef 且在 NotificationReason 中同时具有 SCHEDULEDDECIDED 值的行。

CaseRef NotificationReason NotificationDate
234 SCHEDULED 2022-01-02
234 DECIDED 2022-01-02
123 SCHEDULED 2022-01-01
123 RESCHEDULED 2022-01-02
123 DECIDED 2022-01-03

我写了下面的内容,效果很好,只排除了一行,但我想知道这是否是构造此类查询的最有效方法?

SELECT * 
FROM @Notifications
WHERE CaseRef IN (SELECT CaseRef FROM @Notifications
                  WHERE NotificationReason = 'SCHEDULED')
  AND CaseRef IN (SELECT CaseRef FROM @Notifications
                  WHERE NotificationReason = 'DECIDED')
ORDER BY CaseRef DESC

谢谢。

您的查询对于检查两个状态应该相当快。但是如果你想检查许多状态,替代方法是:

select *
from t
where caseref in (
    select caseref
    from t
    where notificationreason in ('SCHEDULED', 'DECIDED')
    group by caseref
    having count(distinct notificationreason) = 2
)

您的查询没问题,但是 returns 和 NotificationReason 的附加行已重新安排,因此它应该是:

select * FROM Notifications
where CaseRef in (select CaseRef from Notifications
where NotificationReason = 'SCHEDULED')
AND CaseRef in (select CaseRef from Notifications
where NotificationReason = 'DECIDED')
and NotificationReason<>'RESCHEDULED'
order by CaseRef desc

提琴手http://sqlfiddle.com/#!18/2bf412/17 如果您想知道查询的效率,请检查执行计划