假設我有下表:
| 案例參考 | 通知原因 | 通知日期 |
|---|---|---|
| 123 | 預定的 | 2022-01-01 |
| 234 | 預定的 | 2022-01-02 |
| 312 | 預定的 | 2022-01-01 |
| 123 | 改期 | 2022-01-02 |
| 123 | 決定 | 2022-01-03 |
| 234 | 決定 | 2022-01-02 |
如果我只想回傳CaseRef具有 aSCHEDULED且DECIDED在NotificationReason.
| 案例參考 | 通知原因 | 通知日期 |
|---|---|---|
| 234 | 預定的 | 2022-01-02 |
| 234 | 決定 | 2022-01-02 |
| 123 | 預定的 | 2022-01-01 |
| 123 | 改期 | 2022-01-02 |
| 123 | 決定 | 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
謝謝。
uj5u.com熱心網友回復:
您的查詢對于檢查兩種狀態應該相當快。但是,如果您想檢查許多狀態,則替代方法是:
select *
from t
where caseref in (
select caseref
from t
where notificationreason in ('SCHEDULED', 'DECIDED')
group by caseref
having count(distinct notificationreason) = 2
)
uj5u.com熱心網友回復:
您的查詢沒問題,但回傳并帶有 NotificationReason RESCHEDULED 的附加行,因此它應該是:
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
fiddler http://sqlfiddle.com/#!18/2bf412/17 如果你想知道查詢的效率檢查執行計劃
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446855.html
