[英]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.