r/learnSQL • u/myaccountforworkonly • Mar 18 '26
How can this be made into a single query?
It's pulling from the same table but only differ based on the Status we need to get:
LEFT JOIN (
SELECT
WOH.WORKORDERID
, WOH.CREATEDDATE AS WO_DATE_CLOSED
, ROW_NUMBER() OVER(PARTITION BY WOH.WORKORDERID ORDER BY WOH.CREATEDDATE DESC) AS RN
FROM WORK_ORDER_HISTORY_VW WOH
WHERE
WOH.ISDELETED = FALSE
AND WOH.FIELD = 'Status'
AND WOH.NEWVALUE = 'Closed'
) WOH_CLOSE
ON WOH_CLOSE.WORKORDERID = WO.ID
AND WOH_CLOSE.RN = 1
LEFT JOIN (
SELECT
WOH.WORKORDERID
, WOH.CREATEDDATE AS WO_DATE_CANCEL
, ROW_NUMBER() OVER(PARTITION BY WOH.WORKORDERID ORDER BY WOH.CREATEDDATE ASC) AS RN
FROM WORK_ORDER_HISTORY_VW WOH
WHERE
WOH.ISDELETED = FALSE
AND WOH.FIELD = 'Status'
AND WOH.NEWVALUE = 'Cancelled'
) WOH_CANCEL
ON WOH_CANCEL.WORKORDERID = WO.ID
AND WOH_CANCEL.RN = 1
7
Upvotes
1
u/jshine13371 Mar 18 '26 edited Mar 19 '26
Quite literally, it already is a single query...
But I'm guessing you're asking how to refactor so you only have to join to
WORK_ORDER_HISTORY_VWonce. Based on the code provided it looks like you can pretty easily just use theINkeyword like this:1
u/xaomaw Mar 20 '26 edited Mar 20 '26
As far as I understand you do 2 joins because you have to differentiate between
MAX(WOH.NEWVALUE = 'Closed')andMIN(WOH.NEWVALUE = 'Cancelled')?Then you should be able to put this into a single query with only one scan of
WORK_ORDER_HISTORY_VW:You should test if it is okay for you to receive NULL in
WO_DATE_CLOSEDand/orWO_DATE_CANCELdue to theLEFT JOINand how the performance is compared to the window, as theMAX()andMIN()should search within the whole group ofGROUP BY WOH.WORKORDERID. If theCASE WHENis not fulfilled, this column fills with NULL which is ignored byMAX()andMIN().