[英]SQL Server: How to find the result with 2 criteria: one equals certain column; the other doesn't equal another column
[英]SQL:where column not equal return result else result equals blank value
所以我遇到了我一直在處理的SQL查詢(mssql)問題,該查詢具有多語句where子句,其中where語句之一可能返回也可能不返回值。 如果不滿足where條件,該如何返回一個空值並仍然返回其余結果? 我也在使用多個CTE。
這是我的選擇子句:
select cte_devinfo.SerialNumber,
cte_devinfo.DeviceName,
cte_devinfo.DeviceID,
dev_CTE.concurrencies,
(cte_slots.LocationIndex +1) as 'Total Media',
cte_changer.SlotCount, cte_changer.TotalMountErrors, cte_changer.TotalMounts,
cte_mismatch.MismatchSerialNumber
from cte_devinfo, dev_CTE, cte_slots, cte_changer, cte_mismatch
這是我的where子句:
where cte_devinfo.DeviceID = dev_CTE.DeviceParentID
and cte_slots.LocationID = dev_CTE.DeviceParentID
and cte_changer.ChangerID = dev_CTE.DeviceParentID
and cte_mismatch.LocationID = dev_CTE.DeviceParentID
我想在我的where子句中添加以下內容:
and cte_mismatch.MismatchSerialNumber != cte_devinfo.SerialNumber
但是這種情況可能永遠不會發生,如果不能解決,我該如何忽略這種情況而只返回'',以便其余查詢繼續運行?
首先,使用ANSI聯接重寫查詢:
select cte_devinfo.SerialNumber,
cte_devinfo.DeviceName,
cte_devinfo.DeviceID,
dev_CTE.concurrencies,
(cte_slots.LocationIndex +1) as 'Total Media',
cte_changer.SlotCount, cte_changer.TotalMountErrors, cte_changer.TotalMounts,
cte_mismatch.MismatchSerialNumber
from cte_devinfo
inner join dev_CTE on cte_devinfo.DeviceID = dev_CTE.DeviceParentID
left outer join cte_slots on cte_slots.LocationID = dev_CTE.DeviceParentID
left outer join cte_changer on cte_changer.ChangerID = dev_CTE.DeviceParentID
left outer join cte_mismatch on cte_mismatch.LocationID = dev_CTE.DeviceParentID
我將除第一個以外的所有聯接更改為外部聯接,以允許丟失插槽,更換器和不匹配記錄。 但是,仍然需要dev_CTE
,因為所有表都已從中加入到記錄中。
現在,您可以添加一個where
子句,如下所示:
WHERE cte_mismatch.MismatchSerialNumber IS NULL OR cte_mismatch.MismatchSerialNumber != cte_devinfo.SerialNumber
此條件允許MismatchSerialNumber
為NULL
,甚至允許缺少cte_mismatch
記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.