我有这个 sql 查询,它通过交叉引用 EquipmentItemReservations 表来查找 EquipmentItem 的当前状态:
SELECT EI.Id, ER.ReservationType AS Status
FROM EquipmentItems AS EI
INNER JOIN EquipmentItemReservations AS ER ON EI.Id = ER.EquipmentItemId
WHERE IsApproved = 1
AND DateShipped IS NOT NULL
AND DateReturned IS NULL
预订表的 ReservationType 为“已分配”或“已分配”,在适用的情况下显示为“状态”。
我想扩展此查询以获取不符合要求的设备项,并为其余项设置“可用”AS 状态。
我的目标是拥有包含状态(“已分配”、“已分配”或“可用”)的完整项目列表
答案 0 :(得分:0)
我能够通过这个查询实现这一点(使其成为 SQL 视图):
CREATE VIEW view_EquipmentItemStates AS
SELECT EI.Id, ER.ReservationType AS Status
FROM EquipmentItems AS EI LEFT JOIN EquipmentItemReservations AS ER
ON EI.Id = ER.EquipmentItemId
WHERE IsApproved = 1 AND DateShipped IS NOT NULL AND DateReturned IS NULL
UNION SELECT EquipmentItems.Id, 'Available' As Status
FROM EquipmentItems WHERE EquipmentItems.Id NOT IN (
SELECT EI.Id FROM EquipmentItems AS EI LEFT JOIN EquipmentItemReservations AS ER
ON EI.Id = ER.EquipmentItemIdWHERE IsApproved = 1 AND DateShipped IS NOT NULL
AND DateReturned IS NULL)