I have a table below (Input table) and need to update is_latest to true based on priority of status for all combiantion of orderid , merchantId and uniqueId Priorities are:
RETURNED - 1
CANCELLED - 2
SHIPPED - 3
ORDDERED - 4
Input
OrderId |MerchantId | uniqueId | status | is_latest
O1 M1 U1 ORDERED F
O2 M2 U2 ORDERED F
O1 M1 U1 SHIPPED F
O2 M2 U2 SHIPPED F
O2 M2 U2 CANCELLED F
O3 M3 U3 ORDERED F
Result should be:
OrderId |MerchantId | uniqueId | status | is_latest
O1 M1 U1 ORDERED F
O2 M2 U2 ORDERED F
O1 M1 U1 SHIPPED T
O2 M2 U2 SHIPPED F
O2 M2 U2 CANCELLED T
O3 M3 U3 ORDERED T
I saw few examples but none of them were for updating all the combination of columns
Thanks in advance
----------I tried with following Query -----------------------
WITH cte2 AS
(
SELECT OrderId , merchantId , uniqueId,
ROW_NUMBER() OVER (PARTITION BY OrderId , merchantId , iniqueId ORDER BY
CASE order_status
WHEN 'ORDERED' THEN 4
WHEN 'SHIPPED' THEN 3
WHEN 'CANCELLED' THEN 2
WHEN 'RETURNED' THEN 1
ELSE 5
END
) AS rn
FROM table1
)
Update rdyip
SET rdyip.is_latest = 'T'
FROM table rdyip
inner JOIN
cte2
on
rdyip.OrderId = cte2.OrderId and
rdyip.MerchantId = cte2.MerchantId and
rdyip.uniqueId = cte2.uniqueId
where cte2.rn=1
Its updating all the rows as is_latest= 'T'