I am expecting 3 columns: the Order number from TOrder, the last instance (max) OrderEvent ID, and I want to apply case/when to another column (ordereventtypeid).
The order number and last instance works. However, I have been unable to get the third column working. Essentially, I want to pull the last instance of OrderEventId
for each OrderId
, but then apply CASE/WHEN
to that row. What is happening below is that is returning "T&R" delay for all of them rather than only those where the last OrderEventTypeID
is "107".
SELECT
TOrder.OrderNumber
,(SELECT MAX (OrderEventID) FROM TOrderEvent
WHERE TOrderEvent.OrderID = TOrder.OrderID
) AS 'Delay SubQ'
,CASE
WHEN EXISTS (SELECT MAX (OrderEventID) FROM TOrderEvent
WHERE TOrderEvent.OrderID = TOrder.OrderID
AND TOrderEvent.OrderEventTypeID IN (107))
THEN 'T&R Delay'
ELSE ''
END AS 'Delay Case'
FROM
TOrder
WHERE
TOrder.CustomerId IN (14758, 25167)
AND TOrder.OrderDate >= '1/1/2024'
AND TOrder.OrderStatusID NOT IN (1206, 1208)
I have tried using subqueries, joins, etc. When joining TOrderEvent
and using MAX ON TOrderEvent.OrderEventID
, I get a row for each ordereventid rather than a single row for each orderid with only the last instance of the ordereventid.
I am using SSMS 19.0.20209 with Azure hosted SQL as a service.
Try this
SELECT
TOrder.OrderNumber,
oe.MaxOrderEventID AS [Delay SubQ],
CASE
WHEN oe.OrderEventTypeID = 107 THEN 'T&R Delay'
ELSE ''
END AS [Delay Case]
FROM
TOrder
CROSS APPLY
(
SELECT TOP 1
TOrderEvent.OrderEventID AS MaxOrderEventID,
TOrderEvent.OrderEventTypeID
FROM
TOrderEvent
WHERE
TOrderEvent.OrderID = TOrder.OrderID
ORDER BY
TOrderEvent.OrderEventID DESC
) oe
WHERE
TOrder.CustomerId IN (14758, 25167)
AND TOrder.OrderDate >= '2024-01-01'
AND TOrder.OrderStatusID NOT IN (1206, 1208);