Distinguishing which value is obtained from COALESCE by concatenating the value to a different prefix - sql

SELECT COALESCE(grouped_wells.groupforecasting_id,wells.id) as the_id, string_agg(wells.name,', ') as well_name, sum(gas_cd) as gas_cd, date
FROM productions
INNER JOIN completions on completions.id = productions.completion_id
INNER JOIN wellbores on wellbores.id = completions.wellbore_id
INNER JOIN wells on wells.id = wellbores.well_id
INNER JOIN fields on fields.id = wells.field_id
INNER JOIN clusters on clusters.id = fields.cluster_id
LEFT JOIN grouped_wells on grouped_wells.wells_id = wells.id
LEFT JOIN groupforecasting on groupforecasting.id = grouped_wells.groupforecasting_id and groupforecasting.workspace_id = 3
GROUP BY the_id, productions.date
ORDER BY the_id, productions.date
In the above SQL, I am grouping by the_id that results from COALESCE. I want to avoid grouping grouped_wells.groupforecasting_id of equal value to wells.id.
One possible way is to add a prefix depending on which of the two value I got from COALESCE, either add "group_" or "well_".
How to add this conditional prefix to the_id?
If grouped_wells.groupforecasting_id is Null then concatenate "well_" to the result of COALESCE.
Else concatenate "group_" to the result of COALESCE.

You nearly had the solution in your
If grouped_wells.groupforecasting_id is Null then concatenate "well_"
to the result of COALESCE. Else concatenate "group_" to the result of
COALESCE.
In postgres you can use the case when syntax:
case when ... then ...
else ...
end as the_id
completing it in your select (and your comment):
SELECT
case when grouped_wells.groupforecasting_id is NULL then concat('well_', wells.id)
else
concat('group_', grouped_wells.groupforecasting_id)
end as the_id,
string_agg(wells.name,', ') as well_name,
sum(gas_cd) as gas_cd, date
FROM productions
INNER JOIN completions on completions.id = productions.completion_id
INNER JOIN wellbores on wellbores.id = completions.wellbore_id
INNER JOIN wells on wells.id = wellbores.well_id
INNER JOIN fields on fields.id = wells.field_id
INNER JOIN clusters on clusters.id = fields.cluster_id
LEFT JOIN grouped_wells on grouped_wells.wells_id = wells.id
LEFT JOIN groupforecasting on groupforecasting.id = grouped_wells.groupforecasting_id and groupforecasting.workspace_id = 3
GROUP BY the_id, productions.date
ORDER BY the_id, productions.date

Related

DB2 SQL multiple JOIN issue

I have a query with two JOIN and it does not work. I get no errors. It just does not return any records. If I separate my query then it works. What Am I doing wrong here?
When I split up the query I get one record each which is what I should get.
Full query:
SELECT HPOL07.*, #RFC.*, #AAM.*
FROM BPCSPROF.HPOL07
JOIN BPCSPROF.#RFC ON PRFC = #RFC.RFCNUM AND PPRF = #RFC.RFCPRC
AND PGLNO = #RFC.RFCGLN
JOIN BPCSPROF.#AAM ON PPRF = #AAM.AAMPRC AND PGLNO = #AAM.AAMGLN
WHERE PORD = '605400' AND PID <> 'PZ'
Separate queries:
SELECT HPOL07.*, #RFC.*
FROM BPCSPROF.HPOL07
JOIN BPCSPROF.#RFC ON PRFC = #RFC.RFCNUM AND PPRF = #RFC.RFCPRC
AND PGLNO = #RFC.RFCGLN
WHERE PORD = '605400' AND PID <> 'PZ'
SELECT HPOL07.*, #AAM.*
FROM BPCSPROF.HPOL07
JOIN BPCSPROF.#AAM ON PPRF = #AAM.AAMPRC AND PGLNO = #AAM.AAMGLN
WHERE PORD = '605400' AND PID <> 'PZ'
You're doing inner joins, so there must be a record in both #RFC and #AAM for each record in HPOL07...
Is that what you want?
If there's a matching record in #RFC or #AAM, then you'd want to use a LEFT OUTER JOIN
SELECT HPOL07.*, #RFC.*, #AAM.*
FROM BPCSPROF.HPOL07
LEFT OUTER JOIN BPCSPROF.#RFC
ON PRFC = #RFC.RFCNUM AND PPRF = #RFC.RFCPRC
AND PGLNO = #RFC.RFCGLN
LEFT OUTER JOIN BPCSPROF.#AAM
ON PPRF = #AAM.AAMPRC AND PGLNO = #AAM.AAMGLN
WHERE PORD = '605400' AND PID <> 'PZ'
This question could certainly use a table schema but my guess is that PGLNO is a different value between your two joins. If that's the case, the joins aren't going to to work because it is effectively looking for #AAM.AAMGLN = #RFC.RFCGLN in your current query. This is because both joins use the PGLNO value and would need to be the same for both join clauses.
If you want two separate results, #Charles answer should do what you want.
You can also use:
SELECT * FROM A h
LEFT JOIN B pk ON (pk.PKKONZ='010') AND (pk.PKFIRM IN (10, 20 30)) AND h.TPPALN = pk.PKPALN
LEFT JOIN C ar ON (ar.TZKONZ='010') AND (ar.TZFIRM IN (55, 56 ,57)) AND h.TPIDEN = ar.TZIDEN
WHERE ....
ORDER BY ...

Rows which appeared only once in query results

I want to have rows which appeared in 25th of February and did not appear in 6th of March. I've tried to do such query:
SELECT favfd.day, dv.title, array_to_string(array_agg(distinct "host_name"), ',') AS affected_hosts , htmltoText(dsol.fix),
count(dv.title) FROM fact_asset_vulnerability_finding_date favfd
INNER JOIN dim_vulnerability dv USING(vulnerability_id)
INNER JOIN dim_asset USING(asset_id)
INNER JOIN dim_vulnerability_solution USING(vulnerability_id)
INNER JOIN dim_solution dsol USING(solution_id)
INNER JOIN dim_solution_highest_supercedence dshs USING (solution_id)
WHERE (favfd.day='2018-02-25' OR favfd.day='2018-03-06') AND
dsol.solution_type='PATCH' AND dshs.solution_id=dshs.superceding_solution_id
GROUP BY favfd.day, dv.title, host_name, dsol.fix
ORDER BY favfd.day, dv.title
which gave me following results:
results
I've read that I need to add something like "HAVING COUNT(*)=1" but like you can see in query results my count columns looks quite weird. Here is my results with that line added:
results with having
Can you advice me what I am doing wrong?
One way is to use a HAVING clause to assert your date criteria:
SELECT
dv.title,
array_to_string(array_agg(distinct "host_name"), ',') AS affected_hosts,
htmltoText(dsol.fix),
count(dv.title)
FROM fact_asset_vulnerability_finding_date favfd
INNER JOIN dim_vulnerability dv USING(vulnerability_id)
INNER JOIN dim_asset USING(asset_id)
INNER JOIN dim_vulnerability_solution USING(vulnerability_id)
INNER JOIN dim_solution dsol USING(solution_id)
INNER JOIN dim_solution_highest_supercedence dshs USING (solution_id)
WHERE
dsol.solution_type = 'PATCH' AND
dshs.solution_id = dshs.superceding_solution_id
GROUP BY dv.title, dsol.fix
HAVING
SUM(CASE WHEN favfd.day = '2018-02-25' THEN 1 ELSE 0 END) > 0 AND
SUM(CASE WHEN favfd.day = '2018-03-06' THEN 1 ELSE 0 END) = 0
ORDER BY favfd.day, dv.title
The only major changes I made were to remove host_name from the GROUP BY clause, because you use this column in aggregate, in the select clause. And I added the HAVING clause to check your logic.
The change you should make is to replace your implicit join syntax with explicit joins. Putting join criteria into the WHERE clause is considered bad practice nowadays.

SQL Query with counts only returning equivalent counts

I have a query that consists of 1 table and 2 sub queries. The table being a listing of all customers, 1 sub query is a listing all of the quotes given over a period of time for customers and the other sub query is a listing of all of the orders booked for a customer over the same period of time. What I am trying to do is return a result set that is a customer, the number of quotes given, and the number of orders booked over a given period of time. However what I am returning is only a listening of customers over the period of time that have an equivalent quote and order count. I feel like I am missing something obvious within the context of the query but I am unable to figure it out. Any help would be appreciated. Thank you.
Result Set should look like this
Customer-------Quotes-------Orders Placed
aaa----------------4----------------4
bbb----------------9----------------18
ccc----------------18----------------9
select
[Customer2].[Name] as [Customer2_Name],
(count( Quotes.UD03_Key3 )) as [Calculated_CustomerQuotes],
(count( Customer_Bookings.OrderHed_OrderNum )) as [Calculated_CustomerBookings]
from Erp.Customer as Customer2
left join (select
[UD03].[Key3] as [UD03_Key3],
[UD03].[Key4] as [UD03_Key4],
[UD03].[Key1] as [UD03_Key1],
[UD03].[Date02] as [UD03_Date02]
from Ice.UD03 as UD03
inner join Ice.UD02 as UD02 on
UD03.Company = UD02.Company
And
CAST(CAST(UD03.Number09 AS INT) AS VARCHAR(30)) = UD02.Key1
left outer join Erp.Customer as Customer on
UD03.Company = Customer.Company
And
UD03.Key1 = Customer.Name
left outer join Erp.SalesTer as SalesTer on
Customer.Company = SalesTer.Company
And
Customer.TerritoryID = SalesTer.TerritoryID
left outer join Erp.CustGrup as CustGrup on
Customer.Company = CustGrup.Company
And
Customer.GroupCode = CustGrup.GroupCode
where (UD03.Key3 <> '0')) as Quotes on
Customer2.Name = Quotes.UD03_Key1
left join (select
[Customer1].[Name] as [Customer1_Name],
[OrderHed].[OrderNum] as [OrderHed_OrderNum],
[OrderDtl].[OrderLine] as [OrderDtl_OrderLine],
[OrderHed].[OrderDate] as [OrderHed_OrderDate]
from Erp.OrderHed as OrderHed
inner join Erp.Customer as Customer1 on
OrderHed.Company = Customer1.Company
And
OrderHed.BTCustNum = Customer1.CustNum
inner join Erp.OrderDtl as OrderDtl on
OrderHed.Company = OrderDtl.Company
And
OrderHed.OrderNum = OrderDtl.OrderNum) as Customer_Bookings on
Customer2.Name = Customer_Bookings.Customer1_Name
where Quotes.UD03_Date02 >= '5/15/2018' and Quotes.UD03_Date02 <= '5/15/2018' and Customer_Bookings.OrderHed_OrderDate >='5/15/2018' and Customer_Bookings.OrderHed_OrderDate <= '5/15/2018'
group by [Customer2].[Name]
You have several problems going on here. The first problem is your code is so poorly formatted it is user hostile to look at. Then you have left joins being logically treated an inner joins because of the where clause. You also have date literal strings in language specific format. This should always be the ANSI format YYYYMMDD. But in your case your two predicates are contradicting each other. You have where UD03_Date02 is simultaneously greater than and less than the same date. Thankfully you have =. But if your column is a datetime you have prevented any rows from being returned again (the first being your where clause). You have this same incorrect date logic and join in the second subquery as well.
Here is what your query might look like with some formatting so you can see what is going on. Please note I fixed the logical join issue. You still have the date problems because I don't know what you are trying to accomplish there.
select
[Customer2].[Name] as [Customer2_Name],
count(Quotes.UD03_Key3) as [Calculated_CustomerQuotes],
count(Customer_Bookings.OrderHed_OrderNum) as [Calculated_CustomerBookings]
from Erp.Customer as Customer2
left join
(
select
[UD03].[Key3] as [UD03_Key3],
[UD03].[Key4] as [UD03_Key4],
[UD03].[Key1] as [UD03_Key1],
[UD03].[Date02] as [UD03_Date02]
from Ice.UD03 as UD03
inner join Ice.UD02 as UD02 on UD03.Company = UD02.Company
And CAST(CAST(UD03.Number09 AS INT) AS VARCHAR(30)) = UD02.Key1
left outer join Erp.Customer as Customer on UD03.Company = Customer.Company
And UD03.Key1 = Customer.Name
left outer join Erp.SalesTer as SalesTer on Customer.Company = SalesTer.Company
And Customer.TerritoryID = SalesTer.TerritoryID
left outer join Erp.CustGrup as CustGrup on Customer.Company = CustGrup.Company
And Customer.GroupCode = CustGrup.GroupCode
where UD03.Key3 <> '0'
) as Quotes on Customer2.Name = Quotes.UD03_Key1
and Quotes.UD03_Date02 >= '20180515'
and Quotes.UD03_Date02 <= '20180515'
left join
(
select
[Customer1].[Name] as [Customer1_Name],
[OrderHed].[OrderNum] as [OrderHed_OrderNum],
[OrderDtl].[OrderLine] as [OrderDtl_OrderLine],
[OrderHed].[OrderDate] as [OrderHed_OrderDate]
from Erp.OrderHed as OrderHed
inner join Erp.Customer as Customer1 on OrderHed.Company = Customer1.Company
And OrderHed.BTCustNum = Customer1.CustNum
inner join Erp.OrderDtl as OrderDtl on OrderHed.Company = OrderDtl.Company
And OrderHed.OrderNum = OrderDtl.OrderNum
) as Customer_Bookings on Customer2.Name = Customer_Bookings.Customer1_Name
and Customer_Bookings.OrderHed_OrderDate >= '20180515'
and Customer_Bookings.OrderHed_OrderDate <= '20180515'
group by [Customer2].[Name]
COUNT() will just give you the number of records. You'd expect this two result columns to be equal. Try structuring it like this:
SUM(CASE WHEN Quote.UD03_Key1 IS NOT NULL THEN 1 ELSE 0 END) AS QuoteCount,
SUM(CASE WHEN Customer_Bookings.Customer1_Name IS NOT NULL THEN 1 ELSE 0 END) AS custBookingCount

SQL JOIN two tables with null values

I am having a hard time figuring this query out. I need records from issueMaster based on userId and visible, joined to issueActionDetails that are visible, but there may not be any issueActionDetails. I am only getting issues that have actions.
SELECT
b.AssignedTo,
b.Visible,
c.ONEKEY_ID,
C.PHYS_NAME[Doctor],
B.IssueDescription[Issue to Address],
CASE WHEN A.ActionDescription IS NULL THEN 'To Be Assigned' ELSE A.ActionDescription END as [Action],
CASE WHEN A.AssignedTo IS NULL THEN 'To Be Assigned' ELSE A.AssignedTo END as [Assigned To],
CASE WHEN D.[Description] IS NULL THEN 'To Be Assigned' ELSE D.[Description] END As [Status]
FROM [dbo].[tbl_IssueMaster] B
LEFT JOIN [dbo].[tbl_IssueActionDetails] A ON A.IssueID =B.IssueID
INNER JOIN [dbo].[tbl_DoctorsNew] C ON B.OnekeyID =C.ONEKEY_ID
INNER JOIN [dbo].[Action_Status] D ON A.ActionStatus = D.ID
WHERE B.AssignedTo = #UserId AND B.Visible =1 AND A.Visible =1
ORDER BY c.ONEKEY_ID,B.DisplayOrder ,A.DisplayOrder
The "outerness" of the join to tbl_IssueActionDetails is negated by two things:
The inner join to Action_Status:
INNER JOIN [dbo].[Action_Status] D ON A.ActionStatus = D.ID
And the predicate in the WHERE clause
AND A.Visible =1
For any rows returned where there isn't a matching row in tbl_IssueActionDetails, the values in the columns for that table will all be NULL. (The database is essentially creating a row from tbl_IssueActionDetails that consists of all NULLs, and "matching" that row to the row from the table on the left side.
Any predicate that excludes NULL values from columns in that table will exclude that row. If we specify to only return rows where "A.Visible=1", that will exclude any rows that have a NULL value in that column. Which is what I meant when I said the "outerness" of the LEFT JOIN operation was negated.
The fix is to move the predicate to the ON clause of the join to tbl_IssueActionDetail
and change that INNER JOIN to an outer join LEFT JOIN
LEFT JOIN [dbo].[tbl_IssueActionDetails] A
ON A.IssueID = B.IssueID
AND A.Visible = 1
remove "AND A.Visible = 1" from the where clause, add it as a join condition instead
OR, alter the where clause to permit a NULL condition for the LEFT JOIN
WHERE B.AssignedTo = #UserId
AND B.Visible = 1
AND ( A.Visible = 1 OR A.Visible IS NULL)
If you always insist that A.Visible = 1 in the where clause you suppress the NULLs that a LEFT JOIN can provide. Be on guard for this whenever you use an outer join.

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.