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
Related
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
I have this query.
select a.NoSPKJahit as 'TglSPKJahit',
c.TglSPKJahit as 'spkJahit',
a.SeriBarang as 'KodeSeri',
b.NamaBarang as 'NamaBarang',
a.JmlTotalPotong-a.JmlTotalRusakSablon as 'JumlahSPKJahit',
a.JmlTotalSelesaiJahit as 'JumlahHasilJahit',
(select sum(Qty) from PenjualanDTL where KodeBarang = a.KodeBarang) as 'JumlahPenjualan',
(select sum(JumlahRetur) from StokBS where KodeBarang = a.KodeBarang) as 'JumlahRetur',
(select sum(JumlahRusak) from StokBS where KodeBarang = a.KodeBarang) as 'JumlahRusak',
(a.JmlTotalSelesaiJahit - (select sum(Qty) from PenjualanDTL where KodeBarang = a.KodeBarang) +((select sum(JumlahRetur) from StokBS where KodeBarang = a.KodeBarang)-(select sum(JumlahRusak) from StokBS where KodeBarang = a.KodeBarang))) as 'SisaBarang',
(select sum(JumlahStok) from StokToko where KodeBarang = a.KodeBarang and KodeToko = 'GD000')as 'Gudang',
(select sum(JumlahStok) from StokToko where KodeBarang = a.KodeBarang and KodeToko = 'GD001')as 'GudangAtas',
(select sum(JumlahStok) from StokToko where KodeBarang = a.KodeBarang and KodeToko = 'GD002')as 'Mobil',
(select sum(JumlahStok) from StokToko where KodeBarang = a.KodeBarang and KodeToko = 'OL01')as 'MissMode',
(select sum(JumlahStok) from StokToko where KodeBarang = a.KodeBarang and KodeToko = 'TK005')as 'SilverLeafM'
from DetilBarang a
left join MsBarang b on b.KodeBarang = a.KodeBarang
left join SPKJahit c on c.NoSPKJahit = a.NoSPKJahit
but have very slow performace. How can i speed up query performance ?
Thanks.
I'd move the subqueries to the join clause and use conditional aggregation (SUM(CASE WHEN ...) for all the StokToko.JumlahStok sums.
select
db.NoSPKJahit as "TglSPKJahit",
sj.TglSPKJahit as "spkJahit",
db.SeriBarang as "KodeSeri",
mb.NamaBarang as "NamaBarang",
db.JmlTotalPotong - db.JmlTotalRusakSablon as "JumlahSPKJahit",
db.JmlTotalSelesaiJahit as "JumlahHasilJahit",
pd."JumlahPenjualan",
sb."JumlahRetur",
sb."JumlahRusak",
db.JmlTotalSelesaiJahit - pd."JumlahPenjualan" + sb."JumlahRetur" - sb."JumlahRusak"
as "SisaBarang",
st."Gudang",
st."GudangAtas",
st."Mobil",
st."MissMode",
st."SilverLeafM"
from DetilBarang db
left join MsBarang mb on mb.KodeBarang = db.KodeBarang
left join SPKJahit sj on sj.NoSPKJahit = db.NoSPKJahit
left join
(
select
KodeBarang,
sum(Qty) as "JumlahPenjualan"
from PenjualanDTL
group by KodeBarang
) pd on pd.KodeBarang = db.KodeBarang
left join
(
select
KodeBarang,
sum(JumlahRetur) as "JumlahRetur",
sum(JumlahRusak) as "JumlahRusak"
from StokBS
group by KodeBarang
) sb on sb.KodeBarang = db.KodeBarang
left join
(
select
KodeBarang,
sum(case when KodeToko = 'GD000' then JumlahStok end) as "Gudang",
sum(case when KodeToko = 'GD001' then JumlahStok end) as "GudangAtas",
sum(case when KodeToko = 'GD002' then JumlahStok end) as "Mobil",
sum(case when KodeToko = 'OL01' then JumlahStok end) as "MissMode",
sum(case when KodeToko = 'TK005' then JumlahStok end) as "SilverLeafM"
from StokToko
group by KodeBarang
) st on st.KodeBarang = db.KodeBarang
order by db.NoSPKJahit;
Please change the left outer joins to inner joins where appropriate.
Recommended indexes to speed up the query:
create index idx1 on msbarang (kodebarang, namabarang);
create index idx2 on spkjahit (nospkjahit, tglspkjahit);
create index idx3 on penjualandtl (kodebarang, qty);
create index idx4 on stokbs (kodebarang, jumlahretur, jumlahrusak);
create index idx5 on stoktoko (kodebarang, kodetoko, jumlahstok);
This may be as fast as it gets. Without any WHERE clause you are probably querying a lot of data.
you can try this
SELECT A.*, sum(ISNULL(B.qty, 0)) as TotQty
from SiteInformation A
left join ItemSite B on A.SiteID = B.SiteID and A.InvtID = B.InvtID
I Think it will work better than TotQty = (SELECT SUM(Qty) FROM where...)
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, ())
I have the following query .its execution took 15 min .It is too much slowly .
Is there a way to optimize it ?
Query
SELECT
Id,Fees,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Fees ' AS FeesName
,#MonthName AS [MonthName]
INTO ##TempFeesMonthly
from
(
SELECT DISTINCT
1 as Id,sum(((CNTI_THPAYE *(CNTI_THFACT / CNTI_THPAYE)) *
(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*#NumberOfDays)) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
LEFT JOIN
SCHHAYS.dbo.WTTIEINT INT
ON (
TAT.TIE_ID = INT.TIE_ID
)
AND (
TAT.VTAT_IORDRE = INT.TIEI_ORDRE
)
LEFT JOIN
SCHHAYS.dbo.PYCONTRAT CC
ON TAT.PER_ID = CC.PER_ID
AND TAT.CNT_ID = CC.CNT_ID
LEFT JOIN
SCHHAYS.dbo.CMTIERS T
ON TAT.TIE_ID = T.TIE_ID
LEFT JOIN
SCHHAYS.dbo.WTMISS M
ON CC.PER_ID = M.PER_ID
AND CC.CNT_ID = M.CNT_ID
LEFT JOIN
##WTCNTIWeek COT1
ON M.PER_ID = COT1.PER_ID
AND M.CNT_ID = COT1.CNT_ID
INNER JOIN
SCHHAYS.dbo.WTPRH AS PRH
ON M.PER_ID = PRH.PER_ID
AND M.CNT_ID = PRH.CNT_ID
AND M.TIE_ID = PRH.TIE_ID
INNER JOIN
##tempStartEndWeekDates AS Tsed
ON PRH_DTEDEBSEM>=Tsed.StartDate
AND PRH_DTEFINSEM<=Tsed.EndDate
LEFT JOIN
SCHHAYS.dbo.WTSCCT C
ON CC.RGPCNT_ID = C.RGPCNT_ID
AND CC.PER_ID = C.PER_ID
AND CC.CNT_ID = C.CNT_ID
INNER JOIN
##TempHaysStaffWeek HF
ON C.VAPO_CODE = HF.onetouch COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate)t
--CREATE INDEX IDX_TempFeesMonthly ON ##TempFeesMonthly(WeekOfMonth)
--Calcul Temp Margin
UNION ALL
--INSERT INTO ##TempFeesMonthly(Id,Fees,WeekOfMonth,StartDate,EndDate,FeesName,[MonthName])
SELECT
2, sum(Fees) AS Fees ,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Margin ' AS FeesName
,#MonthName AS [MonthName]
from
(
SELECT DISTINCT
sum((CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*#NumberOfDays)-(CNTI_THPAYE *(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*1.453*1.21*#NumberOfDays) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
LEFT JOIN
SCHHAYS.dbo.WTTIEINT INT
ON (
TAT.TIE_ID = INT.TIE_ID
)
AND (
TAT.VTAT_IORDRE = INT.TIEI_ORDRE
)
LEFT JOIN
SCHHAYS.dbo.PYCONTRAT CC
ON TAT.PER_ID = CC.PER_ID
AND TAT.CNT_ID = CC.CNT_ID
LEFT JOIN
SCHHAYS.dbo.CMTIERS T
ON TAT.TIE_ID = T.TIE_ID
LEFT JOIN
SCHHAYS.dbo.WTMISS M
ON CC.PER_ID = M.PER_ID
AND CC.CNT_ID = M.CNT_ID
LEFT JOIN
##WTCNTIWeek COT1
ON M.PER_ID = COT1.PER_ID
AND M.CNT_ID = COT1.CNT_ID
INNER JOIN
SCHHAYS.dbo.WTPRH AS PRH
ON M.PER_ID = PRH.PER_ID
AND M.CNT_ID = PRH.CNT_ID
AND M.TIE_ID = PRH.TIE_ID
INNER JOIN
##tempStartEndWeekDates AS Tsed
ON PRH_DTEDEBSEM>=Tsed.StartDate
AND PRH_DTEFINSEM<=Tsed.EndDate
LEFT JOIN
SCHHAYS.dbo.WTSCCT C
ON CC.RGPCNT_ID = C.RGPCNT_ID
AND CC.PER_ID = C.PER_ID
AND CC.CNT_ID = C.CNT_ID
INNER JOIN
##TempHaysStaffWeek HF
ON C.VAPO_CODE = HF.onetouch COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate,CNTI_THPAYE,CNTI_DURHEBDO)t
GROUP BY WeekOfMonth,StartDate,EndDate
Trying to get the last/lastest record from ShipHead.Shipdate instead of all the records How do i Do last record with this query?
SELECT
OrderRel.ReqDate
,OrderHed.EntryPerson
,ShipHead.ShipDate
,Customer.Name
,ShipDtl.OrderNum
,ShipDtl.OrderLine
,ShipDtl.OrderRelNum
FROM
OrderHed
INNER JOIN OrderDtl
ON OrderHed.Company = OrderDtl.Company AND OrderHed.OrderNum = OrderDtl.OrderNum
INNER JOIN OrderRel
ON OrderDtl.Company = OrderRel.Company AND OrderDtl.OrderNum = OrderRel.OrderNum AND OrderDtl.OrderLine = OrderRel.OrderLine
INNER JOIN ShipDtl
ON OrderRel.Company = ShipDtl.Company AND OrderRel.OrderNum = ShipDtl.OrderNum AND OrderRel.OrderLine = ShipDtl.OrderLine AND OrderRel.OrderRelNum = ShipDtl.OrderRelNum
INNER JOIN ShipHead
ON ShipDtl.Company = ShipHead.Company AND ShipDtl.PackNum = ShipHead.PackNum
INNER JOIN Customer
ON ShipHead.Company = Customer.Company AND ShipHead.CustNum = Customer.CustNum
WHERE
OrderRel.OrderNum = 603205
You could try the following. If you wanted the last dated record for each entry person then change to the B:
SELECT
X.ReqDate,
X.EntryPerson,
X.ShipDate,
X.Name,
X.OrderNum,
X.OrderLine,
X.OrderRelNum
FROM
(
SELECT
ORl.ReqDate,
OH.EntryPerson,
SH.ShipDate,
rn = row_number() OVER(ORDER BY SH.ShipDate DESC),
--rn = row_number() OVER(PARTITION BY OH.EntryPerson ORDER BY SH.ShipDate DESC) --<<B
C.Name,
SD.OrderNum,
SD.OrderLine,
SD.OrderRelNum
FROM
OrderHed OH
INNER JOIN OrderDtl OD ON
OH.Company = OD.Company AND
OH.OrderNum = OD.OrderNum
INNER JOIN OrderRel ORl ON
OD.Company = ORl.Company AND
OD.OrderNum = ORl.OrderNum AND
OD.OrderLine = ORl.OrderLine
INNER JOIN ShipDtl SD ON
ORl.Company = SD.Company AND
ORl.OrderNum = SD.OrderNum AND
ORl.OrderLine = SD.OrderLine AND
ORl.OrderRelNum = SD.OrderRelNum
INNER JOIN ShipHead SH ON
SD.Company = SH.Company AND
SD.PackNum = SH.PackNum
INNER JOIN Customer C ON
SH.Company = C.Company AND
SH.CustNum = C.CustNum
WHERE
ORl.OrderNum = 603205
) X
WHERE X.rn = 1
P.S. why don't you use shorter aliases - that is part of the point of aliases