left outer join doesnt return all rows on left table - sql

set #fuel_type='hsd';
select
ro.ro_id,
(case
when if(#fuel_type='ms',r.ms_field_input_id,r.hsd_field_input_id)= 0
then if(#fuel_type='ms',concat(r.remark_ms,r.remark_branded),r.remark_hsd)
else
f.field_name
end )
from
retail_outlets ro left join
volume_trackers r on ro.ro_id=r.ro_id,
field_inputs_master f
where
if(#fuel_type='ms',r.ms_field_input_id = f.field_id,r.hsd_field_input_id=f.field_id)
and ro.pricing_module=1 and if(#fuel_type='ms',ro.ms,ro.hsd)=1 and r.date_inserted='2017-02-06'
;
I need to show all the ro_id in the retail_outlets table but only the ro_id that match with the volume trackers table are displayes

Not positive but I think this is what you're after.
changes are the following:
removed , notation and inject a left join
moved the r.date_inserted to the join criteria.
moved where clause for , join to new left join and altered to case statement as to why I used a left join... Since we tie back to R which is already a left join it made sense to me to continue with left joins...
removed some unneeded ()'s
Assumptions r.date_inserted is a varchar2 data type or '2017-02-06' is implicitly being cast correctly.
.
SET #fuel_type='hsd';
SELECT
ro.ro_id ,
CASE
WHEN IF(#fuel_type='ms',r.ms_field_input_id,r.hsd_field_input_id)= 0
THEN IF(#fuel_type='ms',concat(r.remark_ms,r.remark_branded),r.remark_hsd)
ELSE f.field_name
END
FROM retail_outlets ro
LEFT JOIN volume_trackers r
ON ro.ro_id = r.ro_id
AND r.date_inserted = '2017-02-06'
LEFT JOIN field_inputs_master f
ON f.field_id = CASE WHEN #fuel_type='ms'
THEN r.ms_field_input_id
ELSE r.hsd_field_input_id
END
WHERE ro.pricing_module=1
AND IF(#fuel_type ='ms',ro.ms,ro.hsd)=1;

Related

Conditional Inner Join with two Functions

I have two functions. I need to decide whether to join with these two based on a BIT Value.
ON APEL.data_Period_dataination_Lookup_ID = CCEL.data_Period_dataination_Lookup_ID
INNER JOIN markcommon.GetPredecessordatadataIds() AS PIDS
IF #Combined_Flag=1
BEGIN
ON PIDS.data_Period_dataination_Identifier = APEL.data_Period_dataination_Identifier
AND PIDS.data_Period_Identifier = APL.data_Period_Identifier
END
Basically
if BIT=0 join with function 1 else join with function 2
I tried putting an IF Clause .. but it does not seem to work. What is the proper way to do it?
Just add your static condition as part of the join condition and use a LEFT JOIN to ensure it works with the missing row. You can then use a case expression in your select to obtain the correct column e.g.
SELECT
CASE WHEN F1.id IS NOT NULL THEN F1.MyColumn ELSE F2.MyColumn END
FROM ...
LEFT JOIN markcommon.Function1() AS F1
ON #Combined_Cohort = 1
AND {The rest of the join conditions}
LEFT JOIN markcommon.Function2() AS F2
ON #Combined_Cohort = 0
AND {The rest of the join conditions}
I think you can just use a LEFT JOIN:
ON APEL.data_Period_dataination_Lookup_ID = CCEL.data_Period_dataination_Lookup_ID LEFT JOIN
markcommon.GetPredecessordatadataIds() PIDS
ON #Combined_Cohort = 1 AND
PIDS.data_Period_dataination_Identifier = APEL.data_Period_dataination_Identifier AND
PIDS.data_Period_Identifier = APL.data_Period_Identifier
. . .
WHERE #Combined_Cohort <> 1 OR PIDS.data_Period_dataination_Identifier IS NOT NULL
You can use the LEFT JOIN as follows:
APEL.data_Period_dataination_Lookup_ID = CCEL.data_Period_dataination_Lookup_ID
LEFT JOIN markcommon.GetPredecessordatadataIds() AS PIDS
ON (#Combined_Flag=1 AND PIDS.data_Period_dataination_Identifier = APEL.data_Period_dataination_Identifier
AND PIDS.data_Period_Identifier = APL.data_Period_Identifier
)
LEFT JOIN FUNCTION2() AS PIDS2
ON (#Combined_Flag=0 AND <<join condition for function 2>>
)
Please also check:
SELECT
IIF(F1.id IS NOT NULL,F1.MyColumn,F2.MyColumn)
FROM ...
LEFT JOIN markcommon.Function1() AS F1
ON #Combined_Cohort = 1
AND {The rest of the join conditions}
LEFT JOIN markcommon.Function2() AS F2
ON #Combined_Cohort != 1
AND {The rest of the join conditions}

Postgresql - Conditional Join if data exist

My current query show the data from the table called "Buque" and has some references from another tables. The problem is when i execute the query it never shows the result because it consumes too much memory i guess.
The current query i have
select buq.buq_codigo, tbu.tbu_codigo, tbu.tbu_nombre, pai.pai_codigo, pai.pai_nombre,
pue.pto_codigo, pue.pto_nombre, lin.lin_codigo, lin.lin_nombre, tra.tra_codigo,
tra.tra_nombre, buq.buq_nombre, buq.buq_des, buq.num_trb, buq.num_eslora,
buq.max_tons, buq.reg_lloyd, buq.buq_codigo1, buq.codigo_omi,
case buq.buq_estado when 'A' then 'Activo' else 'Inactivo' end as buq_estado
from publico.mae_buque as buq, publico.mae_tipbuque as tbu, publico.mae_pais as pai,
publico.mae_puerto as pue, publico.mae_linea as lin, publico.mae_trafico as tra
where buq.tbu_codigo = tbu.tbu_codigo or
buq.pai_codigo = pai.pai_codigo or
buq.pto_codigo = pue.pto_codigo or
buq.lin_codigo = lin.lin_codigo or
buq.tra_codigo = tra.tra_codigo
I also tried with inner joins but the problem is it returns me the data that meets the conditions of the joins. In other words, if the join has data to compare, returns the name, if not, show the null data.
The query must return me 611 records, with inner joins returns 68 records.
Concerning your desired result, use left outer joins, which fill up any non-existing rows of the right hand side table with null-values;
Concerning the out of memory issue, note that you used or to connect your tables; this actually leads to the fact that almost every record of the involved tables is connected to almost every other record (almost a cross join / cartesian product); This can get very large if you connect 6 tables...
select buq.buq_codigo, tbu.tbu_codigo, tbu.tbu_nombre, pai.pai_codigo, pai.pai_nombre,
pue.pto_codigo, pue.pto_nombre, lin.lin_codigo, lin.lin_nombre, tra.tra_codigo,
tra.tra_nombre, buq.buq_nombre, buq.buq_des, buq.num_trb, buq.num_eslora,
buq.max_tons, buq.reg_lloyd, buq.buq_codigo1, buq.codigo_omi,
case buq.buq_estado when 'A' then 'Activo' else 'Inactivo' end as buq_estado
from publico.mae_buque as buq
left outer join publico.mae_tipbuque as tbu on buq.tbu_codigo = tbu.tbu_codigo
left outer join publico.mae_pais as pai on (buq.pai_codigo = pai.pai_codigo)
left outer join publico.mae_puerto as pue on (buq.pto_codigo = pue.pto_codigo)
left outer join publico.mae_linea as lin on (buq.lin_codigo = lin.lin_codigo)
left outer join publico.mae_trafico as tra on (buq.tra_codigo = tra.tra_codigo)
You have to use left outer join:
select *
from
publico.mae_buque as buq
left outer join publico.mae_tipbuque as tbu on (buq.tbu_codigo = tbu.tbu_codigo)
left outer join publico.mae_pais as pai on (buq.pai_codigo = pai.pai_codigo)
left outer join publico.mae_puerto as pue on (buq.pto_codigo = pue.pto_codigo )
left outer join publico.mae_linea as lin on (buq.lin_codigo = lin.lin_codigo)
left outer join publico.mae_trafico as tra on (buq.tra_codigo = tra.tra_codigo);

Access left join not working as I am picturing it

I am trying to write a query that involves 3 tables and left joining two of them onto a main one.
SELECT UNIT_MAIN.UNIT_NO, DEPT_MAIN.LEV_2, Card.CardNumberLong AS [Some
Number], Card.Enabled, F_CARD.CARD_NO, F_CARD.END_DT
FROM (((UNIT_MAIN
INNER JOIN DEPT_MAIN ON UNIT_MAIN.USING_DEPT = DEPT_MAIN.DEPT_ID)
LEFT JOIN Card ON (UNIT_MAIN.UNIT_NO = Card.UnitCode AND Card.Enabled = True) )
LEFT JOIN F_CARD ON (UNIT_MAIN.UNIT_ID = F_CARD.ASSIGNED_ID AND (F_CARD.END_DT) Is Null ))
WHERE (((UNIT_MAIN.STATUS)="A") AND ((DEPT_MAIN.LEV_2)="AM") AND ((Card.Enabled)=True) )
OR (((UNIT_MAIN.STATUS)="D") AND ((DEPT_MAIN.LEV_2)="AM") AND ((Card.Enabled)=True) )
The issue I am having is when F_CARD table has rows where the F_CARD.END_DT is not null, causing the main table (unit table) not to show up even though it is a left join and the F_CARD table rows did not satisfy the join condition (or I am to believe).
I don't have any where clauses on the F_CARD table and they are only on the join condition.
edit
When I perform
LEFT JOIN MFIVE_F_CARD ON (MFIVE_UNIT_DEPT_COMP_MAIN.UNIT_ID = MFIVE_F_CARD.ASSIGNED_ID AND ((MFIVE_F_CARD.END_DT) Is Null)
The unit does not appear if the F_CARD table contained rows that had an END_DT, I was to believe that since the left join condition failed, the inner table (unit table) should appear regardless.
If I remove any F_CARD related values from the query, the missing units I am looking for appear. It is an inner join, left join, left join. When the second left join happens, I lose rows even when they should appear.
I narrowed down my joins and just did the inner with the left with F_CARD. Trying to see why it doesnt return rows where the join fails.
Tried to do the following, however im getting an unsupported join error...
SELECT
UNIT_MAIN.UNIT_NO
,DEPT_MAIN.LEV_2
,Card.CardNumberLong AS [SomeNumber]
,Card.Enabled
,F_CARD.CARD_NO
,F_CARD.END_DT FROM
(
(
(
UNIT_MAIN
INNER JOIN DEPT_MAIN
ON UNIT_MAIN.USING_DEPT = DEPT_MAIN.DEPT_ID
)
LEFT JOIN Card
ON (UNIT_MAIN.UNIT_NO = Card.UnitCode AND Card.Enabled = True)
)
LEFT JOIN F_CARD
ON (UNIT_MAIN.UNIT_ID = F_CARD.ASSIGNED_ID AND F_CARD.END_DT Is Null)
) WHERE
(UNIT_MAIN.STATUS = "A" OR UNIT_MAIN.STATUS = "D")
AND DEPT_MAIN.LEV_2 = "AM"
Thanks.
I have a feeling it's because you have clauses in your joins that are doing boolean checks rather than matching records between the tables, i.e.
Card.Enabled = True and (F_CARD.END_DT) IS NULL
Try changing the query to:
SELECT
UNIT_MAIN.UNIT_NO
,DEPT_MAIN.LEV_2
,Card.CardNumberLong AS [SomeNumber]
,Card.Enabled
,F_CARD.CARD_NO
,F_CARD.END_DT
FROM
(
(
(
UNIT_MAIN
INNER JOIN DEPT_MAIN
ON UNIT_MAIN.USING_DEPT = DEPT_MAIN.DEPT_ID
)
LEFT JOIN Card
ON UNIT_MAIN.UNIT_NO = Card.UnitCode
)
LEFT JOIN F_CARD
ON UNIT_MAIN.UNIT_ID = F_CARD.ASSIGNED_ID
)
WHERE
(UNIT_MAIN.STATUS = "A" OR UNIT_MAIN.STATUS = "D")
AND DEPT_MAIN.LEV_2 = "AM"
AND Card.Enabled = True

LEFT JOIN ON COALESCE(a, b, c) - very strange behavior

I have encountered very strange behavior of my query and I wasted a lot of time to understand what causes it, in vane. So I am asking for your help.
SELECT count(*) FROM main_table
LEFT JOIN front_table ON front_table.pk = main_table.fk_front_table
LEFT JOIN info_table ON info_table.pk = front_table.fk_info_table
LEFT JOIN key_table ON key_table.pk = COALESCE(info_table.fk_key_table, front_table.fk_key_table_1, front_table.fk_key_table_2)
LEFT JOIN side_table ON side_table.fk_front_table = front_table.pk
WHERE side_table.pk = (SELECT MAX(pk) FROM side_table WHERE fk_front_table = front_table.pk)
OR side_table.pk IS NULL
Seems like a simple join query, with coalesce, I've used this technique before(not too many times) and it worked right.
In this query I don't ever get nulls for side_table.pk. If I remove coalesce or just don't use key_table, then the query returns rows with many null side_table.pk, but if I add coalesce join, I can't get those nulls.
It seems key_table and side_table don't have anything in common, but the result is so weird.
Also, when I don't use side_table and WHERE clause, the count(*) result with coalesce and without differs, but I can't see any pattern in rows missing, it seems random!
Real query:
SELECT ECHANGE.EXC_AUTO_KEY, STOCK_RESERVATIONS.STR_AUTO_KEY FROM EXCHANGE
LEFT JOIN WO_BOM ON WO_BOM.WOB_AUTO_KEY = EXCHANGE.WOB_AUTO_KEY
LEFT JOIN VIEW_WO_SUB ON VIEW_WO_SUB.WOO_AUTO_KEY = WO_BOM.WOO_AUTO_KEY
LEFT JOIN STOCK stock3 ON stock3.STM_AUTO_KEY = EXCHANGE.STM_AUTO_KEY
LEFT JOIN STOCK stock2 ON stock2.STM_AUTO_KEY = EXCHANGE.ORIG_STM
LEFT JOIN CONSIGNMENT_CODES con2 ON con2.CNC_AUTO_KEY = stock2.CNC_AUTO_KEY
LEFT JOIN CONSIGNMENT_CODES con3 ON con3.CNC_AUTO_KEY = stock3.CNC_AUTO_KEY
LEFT JOIN CI_UTL ON CI_UTL.CUT_AUTO_KEY = EXCHANGE.CUT_AUTO_KEY
LEFT JOIN PART_CONDITION_CODES pcc2 ON pcc2.PCC_AUTO_KEY = stock2.PCC_AUTO_KEY
LEFT JOIN PART_CONDITION_CODES pcc3 ON pcc3.PCC_AUTO_KEY = stock3.PCC_AUTO_KEY
LEFT JOIN STOCK_RESERVATIONS ON STOCK_RESERVATIONS.STM_AUTO_KEY = stock3.STM_AUTO_KEY
LEFT JOIN WAREHOUSE wh2 ON wh2.WHS_AUTO_KEY = stock2.WHS_ORIGINAL
LEFT JOIN SM_HISTORY ON (SM_HISTORY.STM_AUTO_KEY = EXCHANGE.ORIG_STM AND SM_HISTORY.WOB_REF = EXCHANGE.WOB_AUTO_KEY)
LEFT JOIN RC_DETAIL ON stock3.RCD_AUTO_KEY = RC_DETAIL.RCD_AUTO_KEY
LEFT JOIN RC_HEADER ON RC_HEADER.RCH_AUTO_KEY = RC_DETAIL.RCH_AUTO_KEY
LEFT JOIN WAREHOUSE wh3 ON wh3.WHS_AUTO_KEY = COALESCE(RC_DETAIL.WHS_AUTO_KEY, stock3.WHS_ORIGINAL, stock3.WHS_AUTO_KEY)
WHERE STOCK_RESERVATIONS.STR_AUTO_KEY = (SELECT MAX(STR_AUTO_KEY) FROM STOCK_RESERVATIONS WHERE STM_AUTO_KEY = stock3.STM_AUTO_KEY)
OR STOCK_RESERVATIONS.STR_AUTO_KEY IS NULL
Removing LEFT JOIN WAREHOUSE wh3 gives me about unique EXC_AUTO_KEY values with a lot of NULL STR_AUTO_KEY, while leaving this row removes all NULL STR_AUTO_KEY.
I recreated simple tables with numbers with the same structure and query works without any problems o.0
I have a feeling COALESCE is acting as a REQUIRED flag for the joined table, hence shooting the LEFT JOIN to become an INNER JOIN.
Try this:
SELECT COUNT(*)
FROM main_table
LEFT JOIN front_table ON front_table.pk = main_table.fk_front_table
LEFT JOIN info_table ON info_table.pk = front_table.fk_info_table
LEFT JOIN key_table ON key_table.pk = NVL(info_table.fk_key_table, NVL(front_table.fk_key_table_1, front_table.fk_key_table_2))
LEFT JOIN (SELECT fk_, MAX(pk) as pk FROM side_table GROUP BY fk_) st ON st.fk_ = front_table.pk
NVL might behave just the same though...
I undertood what was the problem (not entirely though): there is a LEFT JOIN VIEW_WO_SUB in original query, 3rd line. It causes this query to act in a weird way.
When I replaced the view with the other table which contained the information I needed, the query started returning right results.
Basically, with this view join, NVL, COALESCE or CASE join with combination of certain arguments did not work along with OR clause in WHERE subquery, all rest was fine. ALthough, I could get the query to work with this view join, by changing the order of joined tables, I had to place table participating in where subquery to the bottom.

SQL Stored Procedure With One To Many Relationship Return Only Most Recent Record

I've been having a terrible time with this. I created a stored procedure to return a corresponding record, but one of the tables has multiple print jobs so it returns multiple records. I only want the most recent requested print job to return and I can't get it to work correctly.
Please help!
SELECT PrintJobs.WORDERKey,
PrintJobs.JobNumber,
WORDER.U_DateRequired AS DateRequired,
ProductMaster.PartFileItemID,
WORDER.ManufacturingDepartment AS MfgDept,
PrintJobs.Copies AS LabelCopies,
PrintJobs.ExpiryDate AS JobExpiryDate,
PrintJobs.Batch,
PrintJobs.JulianDate AS JobJulianDate,
ProductMaster.Description,
ProductMaster.PackFormat,
ProductMaster.IngDec,
ProductMaster.BarCodeNumber,
ProductMaster.CustomerProductCode,
ProductMaster.CriticalInstruction,
ProductMaster.StorageInstruction,
ProductMaster.MixedCaseTitle,
ProductMaster.MixedCode1,
ProductMaster.MixedCode2,
ProductMaster.MixedCode3,
ProductMaster.MixedCode4,
ProductMaster.MixedDescription1,
ProductMaster.MixedDescription2,
ProductMaster.MixedDescription3,
ProductMaster.MixedDescription4,
ProductMaster.MixedIngDec1,
ProductMaster.MixedIngDec2,
ProductMaster.MixedIngDec3,
ProductMaster.MixedIngDec4,
ProductMaster.CookingInstruction,
ProductMaster.LogoFilename,
ProductMaster.ProductExpiryRule,
ExpiryRulesMaster.GS1_AppID,
ProductMaster.LabelTemplateID,
CASE WHEN ProductMaster.PartFileItemID IS NULL THEN 'N' ELSE 'Y' END AS LabelDefExists,
LabelTemplateMaster.FileName,
CASE WHEN [DateFormat] = 'Default' THEN ExpiryRulesMaster.DateFormatString ELSE [DateFormat] END AS DateFormatString,
ExpiryRulesMaster.DateRounding,
ExpiryRulesMaster.ExcludeXmasNewYear,
PART.ExternalShelfLifeTotalDays,
CustomOptions.Tagline,
CustomOptions.ShortName AS CustShortName,
ExpiryRulesMaster.LabelText AS ExpiryRuleLabelText,
ProductMaster.inner_hDescription,
ProductMaster.inner_vDescription,
ProductMaster.inner_CustCode,
ProductMaster.inner_Storage,
ProductMaster.inner_WarningMsg,
ProductMaster.inner_Dateformat,
ProductMaster.inner_SpecialCode,
ProductMaster.LabelType,
ProductMaster.inner_MicroSuiteCode,
ProductMaster.inner_PackWeight,
ProductMaster.inner_JDateFormat,
ProductMaster.CustomOptionID,
ProductMaster.inner_PrintLogo,
PART.NominalWeight,
ProductMaster.IngDec_html,
ProductMaster.IngDec_Active,
PrintJobs.PrintJobsID,
MaxJobs.MaxJob,
PrintJobs.DateEntered
FROM ProductMaster RIGHT OUTER JOIN
(
SELECT Partfileitemid,
--JobNumber,
MAX(dateentered) MaxJob
FROM PrintJobs
GROUP BY PartFileItemID
)
MaxJobs ON ProductMaster.PartFileItemID = MaxJobs.PartFileItemID RIGHT OUTER JOIN
PrintJobs ON PrintJobs.PartFileItemID = MaxJobs.PartFileItemID RIGHT OUTER JOIN
LabelTemplateMaster ON ProductMaster.LabelTemplateID = LabelTemplateMaster.LabelTemplateID LEFT OUTER JOIN
CustomOptions ON ProductMaster.CustomOptionID = CustomOptions.CustomOptionID LEFT OUTER JOIN
ExpiryRulesMaster ON ProductMaster.ProductExpiryRule = ExpiryRulesMaster.ExpiryRule LEFT OUTER JOIN
[F8Extract].[dbo].[WORDER] ON PrintJobs.WORDERKey = WORDER.WORDERKey LEFT OUTER JOIN
[F8Extract].[dbo].[PART] ON ProductMaster.PartFileItemID = Part.PartFileItemID
WHERE PrintJobs.WORDERKey = #WORDERKey
END
Thanks,
Stacy
One way would be to look at TOP and ORDER BY, i.e.
SELECT TOP 1
PrintJobs.WORDERKey,
PrintJobs.JobNumber,
WORDER.U_DateRequired AS DateRequired,
ProductMaster.PartFileItemID,
WORDER.ManufacturingDepartment AS MfgDept,
PrintJobs.Copies AS LabelCopies,
PrintJobs.ExpiryDate AS JobExpiryDate,
PrintJobs.Batch,
PrintJobs.JulianDate AS JobJulianDate,
ProductMaster.Description,
ProductMaster.PackFormat,
ProductMaster.IngDec,
ProductMaster.BarCodeNumber,
ProductMaster.CustomerProductCode,
ProductMaster.CriticalInstruction,
ProductMaster.StorageInstruction,
ProductMaster.MixedCaseTitle,
ProductMaster.MixedCode1,
ProductMaster.MixedCode2,
ProductMaster.MixedCode3,
ProductMaster.MixedCode4,
ProductMaster.MixedDescription1,
ProductMaster.MixedDescription2,
ProductMaster.MixedDescription3,
ProductMaster.MixedDescription4,
ProductMaster.MixedIngDec1,
ProductMaster.MixedIngDec2,
ProductMaster.MixedIngDec3,
ProductMaster.MixedIngDec4,
ProductMaster.CookingInstruction,
ProductMaster.LogoFilename,
ProductMaster.ProductExpiryRule,
ExpiryRulesMaster.GS1_AppID,
ProductMaster.LabelTemplateID,
CASE WHEN ProductMaster.PartFileItemID IS NULL THEN 'N' ELSE 'Y' END AS LabelDefExists,
LabelTemplateMaster.FileName,
CASE WHEN [DateFormat] = 'Default' THEN ExpiryRulesMaster.DateFormatString ELSE [DateFormat] END AS DateFormatString,
ExpiryRulesMaster.DateRounding,
ExpiryRulesMaster.ExcludeXmasNewYear,
PART.ExternalShelfLifeTotalDays,
CustomOptions.Tagline,
CustomOptions.ShortName AS CustShortName,
ExpiryRulesMaster.LabelText AS ExpiryRuleLabelText,
ProductMaster.inner_hDescription,
ProductMaster.inner_vDescription,
ProductMaster.inner_CustCode,
ProductMaster.inner_Storage,
ProductMaster.inner_WarningMsg,
ProductMaster.inner_Dateformat,
ProductMaster.inner_SpecialCode,
ProductMaster.LabelType,
ProductMaster.inner_MicroSuiteCode,
ProductMaster.inner_PackWeight,
ProductMaster.inner_JDateFormat,
ProductMaster.CustomOptionID,
ProductMaster.inner_PrintLogo,
PART.NominalWeight,
ProductMaster.IngDec_html,
ProductMaster.IngDec_Active,
PrintJobs.PrintJobsID,
MaxJobs.MaxJob,
PrintJobs.DateEntered
FROM ProductMaster RIGHT OUTER JOIN
(
SELECT Partfileitemid,
--JobNumber,
MAX(dateentered) MaxJob
FROM PrintJobs
GROUP BY PartFileItemID
)
MaxJobs ON ProductMaster.PartFileItemID = MaxJobs.PartFileItemID RIGHT OUTER JOIN
PrintJobs ON PrintJobs.PartFileItemID = MaxJobs.PartFileItemID RIGHT OUTER JOIN
LabelTemplateMaster ON ProductMaster.LabelTemplateID = LabelTemplateMaster.LabelTemplateID LEFT OUTER JOIN
CustomOptions ON ProductMaster.CustomOptionID = CustomOptions.CustomOptionID LEFT OUTER JOIN
ExpiryRulesMaster ON ProductMaster.ProductExpiryRule = ExpiryRulesMaster.ExpiryRule LEFT OUTER JOIN
[F8Extract].[dbo].[WORDER] ON PrintJobs.WORDERKey = WORDER.WORDERKey LEFT OUTER JOIN
[F8Extract].[dbo].[PART] ON ProductMaster.PartFileItemID = Part.PartFileItemID
WHERE PrintJobs.WORDERKey = #WORDERKey
ORDER BY PrintJobs.Number DESC
Note change the PrintJobs.Number to whatever field specifies the time order.