Total the results of a subquery in group by - sql

I have a query that produces the detailed data I need.
Now I need to change the results to produce a single total by dbo.Contract.Description and dbo.PMTask.Description instead of the individual entries that would comprise the total.
Here's what I have that works:
SELECT dbo.Contract.Description, dbo.PMTask.Description,
CAST(dbo.PMTimeActivity.TimeBillable AS decimal(10, 2)) / 60 *
(SELECT SalesPrice
FROM dbo.ARSalesPrice AS ARSalesPrice_1
WHERE (InventoryID = dbo.InventoryItem.InventoryID) AND (dbo.PMTimeActivity.Date >= EffectiveDate) AND (dbo.PMTimeActivity.Date <= ExpirationDate) AND (dbo.InventoryItem.CompanyID = CompanyID)) AS Amount
FROM dbo.InventoryItem
RIGHT OUTER JOIN dbo.PMTask
INNER JOIN dbo.Contract ON dbo.PMTask.CompanyID = dbo.Contract.CompanyID AND dbo.PMTask.ProjectID = dbo.Contract.ContractID
INNER JOIN dbo.PMTimeActivity ON dbo.PMTask.CompanyID = dbo.PMTimeActivity.CompanyID AND dbo.PMTask.ProjectID = dbo.PMTimeActivity.ProjectID AND dbo.PMTask.TaskID = dbo.PMTimeActivity.ProjectTaskID
ON dbo.InventoryItem.CompanyID = dbo.PMTimeActivity.CompanyID AND dbo.InventoryItem.InventoryID = dbo.PMTimeActivity.LabourItemID
WHERE (dbo.PMTimeActivity.IsCorrected = 0) AND (dbo.PMTimeActivity.IsBillable = 1) AND (dbo.PMTimeActivity.Billed = 0) AND (dbo.PMTimeActivity.DeletedDatabaseRecord <> 1)
How do I change the query such that when I add the following Group By I achieve what I want?
Group By dbo.Contract.Description, dbo.PMTask.Description
Any suggestions most welcome.

Once you correct your query such that it works (there is a missing join table) then just add an outer query which sums the amount and groups as specified e.g.
select ContractDescription, TaskDescription, sum(Amount)
from (
SELECT dbo.[Contract].[Description] ContractDescription, dbo.PMTask.[Description] TaskDescription
, CAST(dbo.PMTimeActivity.TimeBillable AS decimal(10, 2)) / 60 * (
SELECT SalesPrice
FROM dbo.ARSalesPrice AS ARSalesPrice_1
WHERE (InventoryID = dbo.InventoryItem.InventoryID) AND (dbo.PMTimeActivity.[Date] >= EffectiveDate) AND (dbo.PMTimeActivity.[Date] <= ExpirationDate) AND (dbo.InventoryItem.CompanyID = CompanyID
)) AS Amount
FROM dbo.InventoryItem
RIGHT OUTER JOIN dbo.PMTask
INNER JOIN dbo.[Contract] ON dbo.PMTask.CompanyID = dbo.[Contract].CompanyID AND dbo.PMTask.ProjectID = dbo.[Contract].ContractID
INNER JOIN dbo.PMTimeActivity ON dbo.PMTask.CompanyID = dbo.PMTimeActivity.CompanyID AND dbo.PMTask.ProjectID = dbo.PMTimeActivity.ProjectID AND dbo.PMTask.TaskID = dbo.PMTimeActivity.ProjectTaskID
/* What should go here */ ON dbo.InventoryItem.CompanyID = dbo.PMTimeActivity.CompanyID AND dbo.InventoryItem.InventoryID = dbo.PMTimeActivity.LabourItemID
WHERE (dbo.PMTimeActivity.IsCorrected = 0) AND (dbo.PMTimeActivity.IsBillable = 1) AND (dbo.PMTimeActivity.Billed = 0) AND (dbo.PMTimeActivity.DeletedDatabaseRecord <> 1)
) X
group by ContractDescription, TaskDescription;

Grouping sets with an empty set will give you a grand total for your groupings, you could use instead cube however that will also generate sub totals for each of your grouped columns as well.
SELECT dbo.Contract.Description, dbo.PMTask.Description,
CAST(dbo.PMTimeActivity.TimeBillable AS decimal(10, 2)) / 60 *
(SELECT SalesPrice
FROM dbo.ARSalesPrice AS ARSalesPrice_1
WHERE (InventoryID = dbo.InventoryItem.InventoryID) AND (dbo.PMTimeActivity.Date >= EffectiveDate) AND (dbo.PMTimeActivity.Date <= ExpirationDate) AND (dbo.InventoryItem.CompanyID = CompanyID)) AS Amount
FROM dbo.InventoryItem RIGHT OUTER JOIN
dbo.PMTask INNER JOIN
dbo.Contract ON dbo.PMTask.CompanyID = dbo.Contract.CompanyID AND dbo.PMTask.ProjectID = dbo.Contract.ContractID INNER JOIN
dbo.PMTimeActivity ON dbo.PMTask.CompanyID = dbo.PMTimeActivity.CompanyID AND dbo.PMTask.ProjectID = dbo.PMTimeActivity.ProjectID AND dbo.PMTask.TaskID = dbo.PMTimeActivity.ProjectTaskID ON
dbo.InventoryItem.CompanyID = dbo.PMTimeActivity.CompanyID AND dbo.InventoryItem.InventoryID = dbo.PMTimeActivity.LabourItemID
WHERE (dbo.PMTimeActivity.IsCorrected = 0) AND (dbo.PMTimeActivity.IsBillable = 1) AND (dbo.PMTimeActivity.Billed = 0) AND (dbo.PMTimeActivity.DeletedDatabaseRecord <> 1)
Group By Grouping Sets (dbo.Contract.Description, dbo.PMTask.Description, ())

Related

How can I remove the the union from this code?

I am attempting to remove the union in this sub-select due to performance issues. All attempts are unsuccessful because of how the AllocatedCRGReservedQty is calculated. How can I remove the union and combine the 2 select statements?
I was able to remove the union on the other portion of the query because it was based on a single where clause difference.
SELECT SrhCompanyID
,WhsPlantID
,SrhReason
,SrhRequestID
,SrdSeq
,SrdLotID
,SrdItemID
,InvQty
,SrdQty
,SrdSampleApprovedQty
,SrdUOM
,SohSalesOrder
,SohType
,AllocatedCRGReservedQty
FROM
( SELECT DISTINCT
SrhCompanyID
,WhsPlantID
,SrhReason
,SrhRequestID
,SrdSeq
,SrdLotID
,SrdItemID
,AsOfInventory InvQty
,SUM(SrdQty)
OVER (PARTITION BY SrdKey) SrdQty
,SUM(SrdSampleApprovedQty)
OVER (PARTITION BY SrdKey) SrdSampleApprovedQty
,SrdUOM
,SohSalesOrder
,SohType
,(SELECT SUM(SltLotAllocTranQty)
FROM SalesOrderLot
INNER JOIN
SalesOrderLotTran ON SltSolKey = SolKey
WHERE SolCompanyID = SodCompanyID AND
SolBranchID = SodBranchID AND
SolSalesOrder = SodSalesOrder AND
SolSalesOrderDtlKey = SodSalesOrderDtlKey AND
SolWipFgLotID = SrdLotID) AllocatedCRGReservedQty
FROM SampleRequestHdr
INNER JOIN SampleRequestDtl ON SrdSrhKey = SrhKey
INNER JOIN Warehouse ON WhsWhseID = SrhWhseID
INNER JOIN Lot ON LotCompanyID = SrhCompanyID AND
LotItemID = SrdItemID AND
LotID = SrdLotID
INNER JOIN #AsOfInventory ON IntLotKey = LotKey
-- Only include inventory transactions for completed production orders
-- Changed to temptable due to deadlocks on prodorder/prodorderreservation
INNER JOIN SalesOrderDtl ON SodCompanyID = SrhCompanyID AND
SodBranchID = SrdBranchID AND
SodSalesOrder = SrdSalesOrder AND
SodSalesOrderDtlKey = SrdSalesOrderDtlKey
INNER JOIN SalesOrderHdr ON SohCompanyID = SodCompanyID AND
SohBranchID = SodBranchID AND
SohSalesOrder = SodSalesOrder
WHERE SrhCompanyID = #CompanyID AND
((#PlantID <> '*' AND WhsPlantID = #PlantID) OR (#PlantID = '*')) AND
SrhApprovalExpireDate >= #As_Of_Date AND
ISNULL(SrdSampleRejected,'N') = 'N' AND
SohType IN ('Contract','Normal') AND
SrdQty <> 0
) WORK
WHERE ISNULL(AllocatedCRGReservedQty,0) < SrdQty -- if the lot is already allocated for at least the offered qty then don't include it so we don't over-state the gallons offered
UNION ALL -- then get the sample request qty offered for non-contract sales orders or no sales order assigned
SELECT SrhCompanyID
,WhsPlantID
,SrhReason
,SrhRequestID
,SrdSeq
,SrdLotID
,SrdItemID
,InvQty
,SrdQty
,SrdSampleApprovedQty
,SrdUOM
,SohSalesOrder
,SohType
,AllocatedCRGReservedQty
FROM
( SELECT DISTINCT
SrhCompanyID
,WhsPlantID
,SrhReason
,SrhRequestID
,SrdSeq
,SrdLotID
,SrdItemID
,AsOfInventory InvQty
,SUM(SrdQty)
OVER (PARTITION BY SrdKey) SrdQty
,SUM(SrdSampleApprovedQty)
OVER (PARTITION BY SrdKey) SrdSampleApprovedQty
,SrdUOM
,SohSalesOrder
,SohType
,(SELECT SUM(WptTranQty)
FROM WineProgram
CROSS APPLY
FN_CDV_WineProgramLotTranPlusPending(SrdLotID, WpgKey)
INNER JOIN
IntendedUse ON InuKey = WpgInuKey AND
InuIntendedUse = 'CRG'
LEFT JOIN
--ProdOrdDtl (NOLOCK) ON PodKey = wptPodKey
va_CDV_ProdOrder ON PodKey = wptPodKey
WHERE --WptLotID = SrdLotID AND
ISNULL(WptTranType,'') <> 'Pending' AND
((wptPodKey IS NOT NULL AND
(#CompletePOsOnly = 'N' OR -- include all POs
(#CompletePOsOnly = 'Y' AND PohCompleteDate IS NOT NULL))) -- Only include transactions if PO is Complete or if it's a non-PO transaction
OR
wptPodKey IS NULL
)
) AllocatedCRGReservedQty
FROM SampleRequestHdr
INNER JOIN SampleRequestDtl ON SrdSrhKey = SrhKey
INNER JOIN Warehouse ON WhsWhseID = SrhWhseID
INNER JOIN Lot ON LotCompanyID = SrhCompanyID AND
LotItemID = SrdItemID AND
LotID = SrdLotID
INNER JOIN
#AsOfInventory ON IntLotKey = LotKey
LEFT JOIN SalesOrderDtl ON SodCompanyID = SrhCompanyID AND
SodBranchID = SrdBranchID AND
SodSalesOrder = SrdSalesOrder AND
SodSalesOrderDtlKey = SrdSalesOrderDtlKey
LEFT JOIN SalesOrderHdr ON SohCompanyID = SodCompanyID AND
SohBranchID = SodBranchID AND
SohSalesOrder = SodSalesOrder
WHERE SrhCompanyID = #CompanyID AND
((#PlantID <> '*' AND WhsPlantID = #PlantID) OR (#PlantID = '*')) AND
SrhApprovalExpireDate >= #As_Of_Date AND
ISNULL(SrdSampleRejected,'N') = 'N' AND
ISNULL(SrdUseCRGReservation,'N') = 'N' AND -- if the SrdUseCRGReservation flag = "N" then return the sample qty
ISNULL(SohType,'') NOT IN ('Contract','Normal') AND -- offered to reduce the ATP (pseudo reservation until the sample expires or is approved/rejected)
SrdQty <> 0
) WORK

How to use SQL Conditional statements in SQL

I'm working on a BIRT Reporting. What I need to do is, If the Column1 value is Approved, Copy Column 2 value to Column 3 else null
SELECT pr.prnum,prline.prlinenum,prline.itemnum,prline.description,prline.orderqty,prline.ponum,pr.status as "PRSTATUS",
postatusappr.changedate as "POAPPRDATE", matrectrans.actualdate as "ACTUALDELIVDATE", prstatuswappr.changedate as "PRCREATED",
prstatusappr.changedate as "PRAPPRDATE", days (current date) - days(date(prstatusappr.changedate)) as "NOOFDAYSAFTERPRAPPR",
INTEGER(days (current date) - days(date(prstatusappr.changedate)))/7 as "NOOFWEEKSAFTERPRAPPR",
INTEGER(days (current date) - days(date(postatusappr.changedate)))/7 as "NOOFWEEKSAFTERPOAPPR" FROM pr pr
LEFT JOIN prline prline ON prline.prnum = pr.prnum AND prline.siteid = pr.siteid
LEFT JOIN poline poline ON poline.ponum = prline.ponum AND poline.siteid = pr.siteid
LEFT JOIN postatus postatusappr ON postatusappr.ponum = poline.ponum AND postatusappr.siteid = pr.siteid AND postatusappr.status = 'APPR'
LEFT JOIN matrectrans matrectrans ON matrectrans.ponum = poline.ponum AND matrectrans.polinenum = poline.polinenum AND matrectrans.positeid = pr.siteid AND matrectrans.issuetype='RECEIPT' AND matrectrans.status = 'COMP'
LEFT JOIN prstatus prstatuswappr ON prstatuswappr.prnum = pr.prnum AND prstatuswappr.status = 'WAPPR' AND prstatuswappr.siteid = pr.siteid
LEFT JOIN prstatus prstatusappr ON prstatusappr.prnum = pr.prnum AND prstatusappr.status = 'APPR' AND prstatusappr.siteid = pr.siteid
where prline.itemnum is not null;
You may try doing an UPDATE with a CASE expression, something like this:
UPDATE yourTable
SET Column3 = CASE WHEN Column1 = 'Approved' THEN Column2 ELSE NULL END;

SQL Query - How to suppress repeating values in the result set?

I'm trying to suppress the repeating values in TotalCarton column. Have tried to replace the value either blank or null but went failed. Any help?
Here is the SQL Script:
SELECT ORDERS.StorerKey,
ORDERS.OrderKey,
PackKey = (SELECT MAX(PackKey) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE ORderKey = ORDERS.OrderKey),
PackHU = BAX_PACK_DTL.OuterPackID,
SalesOrderNum = ( SELECT Upper(Max(ORDERDETAIL.CustShipInst01)) FROM ORDERDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey),
DeliveryNum = Upper(ORDERS.ExternOrderKey),
TotalCarton = ( CASE BAX_PACK_DTL.PackType WHEN 'C' THEN Count(DISTINCT(BAX_PACK_DTL.OuterPackID))
ELSE 0 END ),
TotalPallet = ( CASE BAX_PACK_DTL.PackType WHEN 'P' THEN Count(DISTINCT(BAX_PACK_DTL.OuterPackID))
ELSE 0 END ),
SumCarton = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE PackType = 'C' AND PackKey = '0000000211'),
SumPallet = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE PackType = 'P' AND PackKey = '0000000211'),
AddWho = Upper(ORDERS.EditWho),
ORDERS.AddDate
FROM ORDERS WITH (NOLOCK) INNER JOIN ORDERDETAIL WITH (NOLOCK) ON ORDERS.StorerKey = ORDERDETAIL.StorerKey
AND ORDERS.OrderKey = ORDERDETAIL.OrderKey
INNER JOIN PICKDETAIL WITH (NOLOCK) ON ORDERDETAIL.StorerKey = PICKDETAIL.StorerKey
AND ORDERDETAIL.OrderKey = PICKDETAIL.OrderKey
AND ORDERDETAIL.OrderLineNumber = PICKDETAIL.OrderLineNumber
INNER JOIN BAX_PACK_DTL WITH (NOLOCK) ON PICKDETAIL.OrderKey = BAX_PACK_DTL.OrderKey
AND PICKDETAIL.PickDetailKey = BAX_PACK_DTL.PickDetailKey
WHERE (SELECT COUNT(DISTINCT(ORDERKEY)) FROM PICKDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey ) > 0
AND BAX_PACK_DTL.PackKey = '0000000211'
AND BAX_PACK_DTL.OuterPackID IN
('P111111111',
'P22222222',
'P33333333')
GROUP BY ORDERS.StorerKey,
ORDERS.OrderKey,
ORDERS.ExternOrderKey,
ORDERS.HAWB,
ORDERS.SO,
ORDERS.EditWho,
ORDERS.AddDate,
PICKDETAIL.WaveKey,
BAX_PACK_DTL.OuterPackID,
BAX_PACK_DTL.PackKey,
BAX_PACK_DTL.PackType
ORDER BY BAX_PACK_DTL.OuterPackID ASC
Below is the current result set based on the query above.
Your code looks really strange. I would expect the query to use conditional aggregation and look more like this:
SELECT ORDERS.StorerKey, ORDERS.OrderKey,
PackKey = (SELECT MAX(PackKey) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE ORderKey = ORDERS.OrderKey),
PackHU = BAX_PACK_DTL.OuterPackID,
SalesOrderNum = ( SELECT Upper(Max(ORDERDETAIL.CustShipInst01)) FROM ORDERDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey),
DeliveryNum = Upper(ORDERS.ExternOrderKey),
TotalCarton = COUNT(DISTINCT CASE BAX_PACK_DTL.PackType WHEN 'C' THEN BAX_PACK_DTL.OuterPackID END),
TotalPallet = COUNT(DISTINCT CASE BAX_PACK_DTL.PackType WHEN 'P' THEN BAX_PACK_DTL.OuterPackID END),
SumCarton = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL bpd WHERE pbd.PackType = 'C' AND pbd.PackKey = '0000000211'),
SumPallet = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL bpd WHERE pbd.PackType = 'P' AND pbd.PackKey = '0000000211'),
AddWho = Upper(ORDERS.EditWho),
ORDERS.AddDate
FROM . . .
GROUP BY ORDERS.StorerKey, ORDERS.OrderKey, Upper(ORDERS.ExternOrderKey),
Upper(ORDERS.EditWho), ORDERS.AddDate;
This may not be exact. You have not qualified column names, given the table structure, and are using very arcane query syntax, mixing subqueries and aggregations. But it should give an idea.

How to implement LIMIT with the below microsoft server query

I have long sql query which is taking around 35 seconds to execute the data. So i want to limit the data to 10 records each with offset and limit like mysql to the below mssql query?
SELECT distinct PAsGroupBuyData.groupPA, PAsGroupBuyData.dateShipOn, PAsGroupBuyData.dateShipOn2, PAsGroupBuyData.packingSlipsMade, PAsGroupBuyData.productionTime, PAsGroupBuyData.reorder, DSD.designName, DSD.designCode, DSD.designId,
DSD.dsId, PAsGroupBuyData.machineId, orderType = 1
FROM Quotes_Manufacturer INNER JOIN
PAsData ON PAsData.PA = Quotes_Manufacturer.PA INNER JOIN
PAsGroupBuyData ON PAsGroupBuyData.groupPA = PAsData.GroupPa INNER JOIN
DesignSystemDesigns DSD ON PAsGroupBuyData.designId = DSD.designId
WHERE (PAsGroupBuyData.status = 3) AND (Quotes_Manufacturer.accepted = 1) and (PAsGroupBuyData.dateShipOn <> '".$thisSunday."') and (PAsGroupBuyData.dateShipOn <> '".$lastSunday."')
UNION ALL
SELECT distinct PAsGroupBuyData.groupPA, PAsGroupBuyData.dateShipOn, PAsGroupBuyData.dateShipOn2, PAsGroupBuyData.packingSlipsMade, PAsGroupBuyData.productionTime, PAsGroupBuyData.reorder, DSD.designName, DSD.designCode, DSD.designId,
DSD.dsId, PAsGroupBuyData.machineId, orderType = 2
FROM Quotes_SupplierAndManufacturerGroupBuy INNER JOIN
PAsGroupBuyData ON PAsGroupBuyData.groupPA = Quotes_SupplierAndManufacturerGroupBuy.groupPA INNER JOIN
DesignSystemDesigns DSD ON PAsGroupBuyData.designId = DSD.designId INNER JOIN
PAsData ON PAsData.GroupPa = PAsGroupBuyData.groupPA
WHERE (PAsGroupBuyData.status = 3) AND (Quotes_SupplierAndManufacturerGroupBuy.accepted = 1) and (PAsGroupBuyData.dateShipOn <> '".$thisSunday."') and (PAsGroupBuyData.dateShipOn <> '".$lastSunday."')
UNION ALL
SELECT PAsData.PA, PAsData.dateShipOn, PAsData.dateShipOn2, PAsData.packingSlipsMade, PAsData.productionTime, PAsData.reorder, DSD.designName, DSD.designCode, DSD.designId, DSD.dsId,
PAsData.machineId, orderType = 3
FROM Quotes_Manufacturer INNER JOIN
PAsData ON PAsData.PA = Quotes_Manufacturer.PA INNER JOIN
DesignSystemDesigns DSD ON PAsData.designId = DSD.designId
WHERE (Quotes_Manufacturer.accepted = 1) AND (PAsData.status = 3) AND (PAsData.GroupPa = 0) and (PAsData.dateShipOn <> '".$thisSunday."') and (PAsData.dateShipOn <> '".$lastSunday."')
UNION ALL
SELECT PAsData.PA, PAsData.dateShipOn, PAsData.dateShipOn2, PAsData.packingSlipsMade, PAsData.productionTime, PAsData.reorder, DSD.designName, DSD.designCode, DSD.designId, DSD.dsId,
PAsData.machineId, orderType = 4
FROM Quotes_SupplierAndManufacturer INNER JOIN
PAsData ON PAsData.PA = Quotes_SupplierAndManufacturer.PA INNER JOIN
DesignSystemDesigns DSD ON PAsData.designId = DSD.designId
WHERE (PAsData.status = 3) AND (Quotes_SupplierAndManufacturer.accepted = 1) AND (Pasdata.groupPa = 0) and (PAsData.dateShipOn <> '".$thisSunday."') and (PAsData.dateShipOn <> '".$lastSunday."')
UNION ALL
SELECT ID As PA, _Date As dateShipOn, _Date As dateShipOn2, 0 As packingSlipsMade, productionTime, 0 As reorder, Title As designName, ' ' As designCode, 0 As designId, 0 As dsId,
machineId, orderType = 5
FROM Calendar
WHERE (_Date <> '".$thisSunday."') and (_Date <> '".$lastSunday."') and (_Date > getDate()-1) and (_Date < (getDate()+30))
ORDER BY PAsGroupBuyData.dateShipOn, PAsGroupBuyData.machineId, PAsGroupBuyData.groupPA
Thanks to Gordon. I have found the correct syntax to use offset and limit with mssql queries.
Example: offset ".$offset." ROWS FETCH NEXT ".$limit." ROWS ONLY

Selecting rows with MAX(Column value), DISTINCT by another column in SQL

I have two tables that I'm having difficulty with. OrderHed & UD11. OrderHed has 1 value for OrderNum=70960, but UD11 has 4 records for 70960.
I'm trying to return the max value of UD11.Key5 as a distinct record - what am I doing wrong?
Thanks!
SELECT TOP (100) PERCENT OrderHed.OrderNum,
OrderHed.OpenOrder,
OrderHed.OrderDate,
OrderRel.Plant,
OrderHed.EntryPerson,
OrderHed.Company,
Erp.Customer.CustID,
Erp.Customer.NAME,
Erp.InvcDtl.InvoiceNum,
SUM(OrderDtl.ExtPriceDtl) AS Expr1,
OrderHed.PONum,
Ice.UD11.Key1,
Ice.UD11.Key2,
Ice.UD11.Key3,
Ice.UD11.Key4,
MAX(Ice.UD11.Key5) AS Expr2,
Ice.UD11.Character01,
Ice.UD11.Number01,
Ice.UD11.Date01,
Ice.UD11.Date02,
Ice.UD11.Date03,
Ice.UD11.ShortChar01,
Ice.UD11.ShortChar02,
Ice.UD11.ShortChar03,
Ice.UD11.ShortChar04,
Ice.UD11.ShortChar05,
OrderHed.OrderComment
FROM Erp.Customer
RIGHT JOIN Ice.UD11
RIGHT JOIN Erp.OrderHed AS OrderHed ON Ice.UD11.Company = OrderHed.Company
AND Ice.UD11.Key1 = OrderHed.OrderNum
LEFT JOIN Erp.OrderRel AS OrderRel
RIGHT JOIN Erp.OrderDtl AS OrderDtl ON OrderRel.Company = OrderDtl.Company
AND OrderRel.OrderNum = OrderDtl.OrderNum
AND OrderRel.OrderLine = OrderDtl.OrderLine ON OrderHed.Company = OrderDtl.Company
AND OrderHed.OrderNum = OrderDtl.OrderNum ON Erp.Customer.Company = OrderHed.Company
AND Erp.Customer.CustNum = OrderHed.CustNum LEFT JOIN Erp.InvcDtl RIGHT JOIN Erp.ShipDtl ON Erp.InvcDtl.Company = Erp.ShipDtl.Company
AND Erp.InvcDtl.OrderNum = Erp.ShipDtl.OrderNum
AND Erp.InvcDtl.OrderLine = Erp.ShipDtl.OrderLine
AND Erp.InvcDtl.OrderRelNum = Erp.ShipDtl.OrderRelNum ON OrderRel.Company = Erp.ShipDtl.Company
AND OrderRel.OrderNum = Erp.ShipDtl.OrderNum
AND OrderRel.OrderLine = Erp.ShipDtl.OrderLine
AND OrderRel.OrderRelNum = Erp.ShipDtl.OrderRelNum GROUP BY OrderHed.OrderNum,
OrderHed.OrderDate,
OrderRel.Plant,
OrderHed.EntryPerson,
OrderHed.Company,
OrderHed.OpenOrder,
Erp.Customer.CustID,
Erp.Customer.NAME,
Erp.InvcDtl.InvoiceNum,
OrderHed.PONum,
Ice.UD11.Key1,
Ice.UD11.Key2,
Ice.UD11.Key3,
Ice.UD11.Key4,
Ice.UD11.Character01,
Ice.UD11.Number01,
Ice.UD11.Date01,
Ice.UD11.Date02,
Ice.UD11.Date03,
Ice.UD11.ShortChar01,
Ice.UD11.ShortChar02,
Ice.UD11.ShortChar03,
Ice.UD11.ShortChar04,
Ice.UD11.ShortChar05,
OrderHed.OrderComment HAVING (OrderHed.Company = N'011')
AND (Erp.InvcDtl.InvoiceNum IS NULL)
AND (OrderHed.OrderNum = 70960)
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY OrderNum ORDER BY key5 DESC) rn
FROM (... /* my huge query */) q
) q
WHERE rn = 1