SQL Server 2008 filtering - sql

I am joining 4 tables together from the same db. My query is returning the data i am after, but is also returning multiple rows for some records. I only want the row with the most recent LastReportedHrsDate for each WKO_WorkOrderID. Can someone help me with the correct code to filter?
Code (I am still pretty new to SQL..):
SELECT dbo.PLT.PLT_ItemID, SUM(dbo.PLD.PLD_IssueQty) AS Issued, dbo.WKO.WKO_WorkOrderID, dbo.WKO.WKO_RequiredQty, dbo.WKO.WKO_CompleteQty,
dbo.WKO.WKO_RequiredQty - dbo.WKO.WKO_CompleteQty AS openbalance, dbo.PLT.PLT_QtyPerAssy,
(dbo.WKO.WKO_CompleteQty * dbo.PLT.PLT_QtyPerAssy - SUM(dbo.PLD.PLD_IssueQty)) * - 1 AS WIP, dbo.WKO.WKO_ItemID, dbo.WOO.WOO_StatusCode,
dbo.WOO.WOO_LastReportedHrsDate, dbo.WOO.WOO_WorkCenterID
FROM dbo.PLT INNER JOIN
dbo.PLD ON dbo.PLT.PLT_RecordID = dbo.PLD.PLD_PLT_RecordID INNER JOIN
dbo.WKO ON dbo.PLT.PLT_WorkOrderID = dbo.WKO.WKO_WorkOrderID LEFT OUTER JOIN
dbo.WOO ON dbo.PLT.PLT_WorkOrderID = dbo.WOO.WOO_WorkOrderID
WHERE (dbo.WKO.WKO_StatusCode = N'Released') AND (dbo.PLT.PLT_ItemID = '9005-20-1794')
GROUP BY dbo.PLT.PLT_ItemID, dbo.WKO.WKO_WorkOrderID, dbo.WKO.WKO_RequiredQty, dbo.WKO.WKO_CompleteQty, dbo.PLT.PLT_QtyPerAssy, dbo.WKO.WKO_ItemID,
dbo.WOO.WOO_StatusCode, dbo.WOO.WOO_LastReportedHrsDate, dbo.WOO.WOO_WorkCenterID
HAVING (SUM(dbo.PLD.PLD_IssueQty) = dbo.WKO.WKO_RequiredQty * dbo.PLT.PLT_QtyPerAssy) AND (dbo.WOO.WOO_LastReportedHrsDate IS NOT NULL) AND
(dbo.WOO.WOO_StatusCode IS NOT NULL)
ORDER BY dbo.WKO.WKO_WorkOrderID
Can't post a pic of my results

Please try this:
SELECT max(dbo.WOO.WOO_LastReportedHrsDate),dbo.PLT.PLT_ItemID, SUM(dbo.PLD.PLD_IssueQty) AS Issued, dbo.WKO.WKO_WorkOrderID, dbo.WKO.WKO_RequiredQty, dbo.WKO.WKO_CompleteQty,
dbo.WKO.WKO_RequiredQty - dbo.WKO.WKO_CompleteQty AS openbalance, dbo.PLT.PLT_QtyPerAssy,
(dbo.WKO.WKO_CompleteQty * dbo.PLT.PLT_QtyPerAssy - SUM(dbo.PLD.PLD_IssueQty)) * - 1 AS WIP, dbo.WKO.WKO_ItemID, dbo.WOO.WOO_StatusCode,
dbo.WOO.WOO_WorkCenterID
FROM dbo.PLT INNER JOIN
dbo.PLD ON dbo.PLT.PLT_RecordID = dbo.PLD.PLD_PLT_RecordID INNER JOIN
dbo.WKO ON dbo.PLT.PLT_WorkOrderID = dbo.WKO.WKO_WorkOrderID LEFT OUTER JOIN
dbo.WOO ON dbo.PLT.PLT_WorkOrderID = dbo.WOO.WOO_WorkOrderID
WHERE (dbo.WKO.WKO_StatusCode = N'Released') AND (dbo.PLT.PLT_ItemID = '9005-20-1794')
AND (dbo.WOO.WOO_LastReportedHrsDate IS NOT NULL) AND (dbo.WOO.WOO_StatusCode IS NOT NULL)
GROUP BY dbo.PLT.PLT_ItemID, dbo.WKO.WKO_WorkOrderID, dbo.WKO.WKO_RequiredQty, dbo.WKO.WKO_CompleteQty, dbo.PLT.PLT_QtyPerAssy, dbo.WKO.WKO_ItemID,
dbo.WOO.WOO_StatusCode, dbo.WOO.WOO_WorkCenterID
HAVING (SUM(dbo.PLD.PLD_IssueQty) = dbo.WKO.WKO_RequiredQty * dbo.PLT.PLT_QtyPerAssy)
ORDER BY dbo.WKO.WKO_WorkOrderID

Related

UPDATE statement with JOIN in SQL Server Not Working as Expected

I'm attempting to update the LAST_INSPECTION_FW field for all records in the VEHICLES_FW table with the last JOB_DATE_FW for records with the REASON_CODE_FW = 35. However, what's happening is that once the below code is executed, it's not taking into consideration the WHERE clause. This causes all of the records to update when it should just be updating those with the REASON_CODE_FW = 35.
Is there a way to restructure this code to get it working correctly? Please help, thanks!
UPDATE VEHICLES_FW
SET VEHICLES_FW.LAST_INSPECTION_FW = JOB_HEADERS_FW.FIELD2MAX
FROM VEHICLES_FW
INNER JOIN (SELECT VEHICLE_ID_FW, MAX(JOB_DATE_FW) AS FIELD2MAX
FROM JOB_HEADERS_FW
GROUP BY VEHICLE_ID_FW) AS JOB_HEADERS_FW
ON VEHICLES_FW.VEHICLE_ID_FW = JOB_HEADERS_FW.VEHICLE_ID_FW
INNER JOIN JOB_DETAILS_FW
ON JOB_NUMBER_FW = JOB_NUMBER_FW
WHERE REASON_CODE_FW = '35'
Common Table Expressions are your friend here. SQL Server's strange UPDATE ... FROM syntax is not. EG
with JOB_HEADERS_FW_BY_VEHICLE_ID as
(
SELECT VEHICLE_ID_FW, MAX(JOB_DATE_FW) AS FIELD2MAX
FROM JOB_HEADERS_FW
GROUP BY VEHICLE_ID_FW
), q as
(
Select VEHICLES_FW.LAST_INSPECTION_FW, JOB_HEADERS_FW_BY_VEHICLE_ID.FIELD2MAX NEW_LAST_INSPECTION_FW
FROM VEHICLES_FW
INNER JOIN JOB_HEADERS_FW_BY_VEHICLE_ID
ON VEHICLES_FW.VEHICLE_ID_FW = JOB_HEADERS_FW_BY_VEHICLE_ID.VEHICLE_ID_FW
INNER JOIN JOB_DETAILS_FW
ON JOB_NUMBER_FW = JOB_NUMBER_FW
WHERE REASON_CODE_FW = '35'
)
UPDATE q set LAST_INSPECTION_FW = NEW_LAST_INSPECTION_FW
I suspect this does what you want:
update v
set last_inspection_fw = (
select max(j.job_date_fw)
from job_headers_fw j
inner join job_details_fw jd on jd.job_number_fw = j.job_number_fw
where j.vehicle_id_fw = v.vehicle_id_fw and jd.reason_code_fw = 35
)
from vehicles_fw v

SQL: If there are two rows that contain same record, want it to display one

based on my question above, below is the SQL
SELECT ets_tools.tools_id, ets_borrower.fullname, ets_team.team_name, ets_borrow.time_from,
ets_borrow.time_to, ets_borrow.borrow_id FROM ets_tools
INNER JOIN ets_tools_borrow ON ets_tools.tools_id = ets_tools_borrow.tools_id
INNER JOIN ets_borrow ON ets_borrow.borrow_id = ets_tools_borrow.borrow_id
INNER JOIN ets_borrower ON ets_borrower.badgeid = ets_borrow.badgeid
INNER JOIN ets_team ON ets_team.team_id = ets_borrower.team_id
WHERE ets_tools.borrow_id IS NOT NULL AND ets_borrow.status_id = 1 AND ets_borrow.time_to IS NULL
and the result display like this:
From the image above, we can see that the borrow_id with value 1 display two rows. Now, how to display only one borrow_id for value 1 since its duplicate the same things.
Anyone can help?
Assuming you want to retain the record having the smallest tools_id, you could aggregate by the other columns and take the MIN of tools_id:
SELECT
MIN(ets_tools.tools_id) AS tools_id,
ets_borrower.fullname,
ets_team.team_name,
ets_borrow.time_from,
ets_borrow.time_to,
ets_borrow.borrow_id
FROM ets_tools
INNER JOIN ets_tools_borrow ON ets_tools.tools_id = ets_tools_borrow.tools_id
INNER JOIN ets_borrow ON ets_borrow.borrow_id = ets_tools_borrow.borrow_id
INNER JOIN ets_borrower ON ets_borrower.badgeid = ets_borrow.badgeid
INNER JOIN ets_team ON ets_team.team_id = ets_borrower.team_id
WHERE
ets_tools.borrow_id IS NOT NULL AND
ets_borrow.status_id = 1 AND
ets_borrow.time_to IS NULL
GROUP BY
ets_borrower.fullname,
ets_team.team_name,
ets_borrow.time_from,
ets_borrow.time_to,
ets_borrow.borrow_id;
Try this:
Change the SELECT to SELECT TOP 1 WITH TIES
And at the end add ORDER BY ROW_NUMBER() OVER(PARTITION BY ets_borrow.borrow_id ORDER BY ets_tools.tools_id)

T-SQL Full Outer Join (sample provided)

I have some issues getting a full outer join to work in T-SQL. The left outer join part seems to be working okay, but the right outer join doesn't work as expected. Here's some sample data to test this on:
I have a table A with the following columns and data. The row marked with red is the row that cannot be found in table B.
And a second table B with the following columns and data. The rows marked with yellow are the rows that cannot be found in table A.
I am trying to join the tables using the following sql code:
select tableA.klientnr, tableA.uttakstype, tableA.uttaksnr, tableA.vareanr TableAItem,tableB.vareanr tableBitem, tableA.kvantum tableAquantity, tableB.totkvant tableBquantity
from tableA as tableA
full outer join tableB as tableB on tableA.klientnr=tableB.klientnr and tableA.uttakstype=tableB.uttakstype and tableA.uttaksnr=tableB.uttaksnr and tableA.vareanr=tableB.vareanr and tableB.IsDeleted=0
where tableA.UttaksNr=639779 and tableA.IsDeleted=0
The result of the sql is the following image. The row marked in red is the extra row from tableA that does show up, but I can't get the rows from table B to show up
Expected to have 2 extra rows
550 SA 639779 NULL 100059 NULL 0
550 SA 639779 NULL 103040 NULL 14
Later edit:
Would this be correct way to handle the full outer join where there's the header/line type of structure? Or can the query be optimized?
SELECT ISNULL(q1.accountid, q2.accountid) AccountId
,ISNULL(q1.klientnr, q2.klientnr) KlientNr
,ISNULL(q1.tilgangstype, q2.tilgangstype) 'Reception Type'
,ISNULL(q1.tilgangsnr, q2.tilgangsnr) 'Reception No'
,ISNULL(q1.dato, q2.dato) dato
,ISNULL(q1.LevNr, q2.LevNr) LevNr
,ISNULL(q1.Pakkemerke, q2.Pakkemerke) Pakkemerke
,ISNULL(q1.VareANr, q2.VareANr) VareANr
,ISNULL(q1.Ankomstdato,q2.Ankomstdato) 'Arrival Date'
,q1.Antall1
,q1.totkvant1
,q1.Antall2
,q1.totkvant2
,q2.Antall
,q2.totkvant
,q2.AntallTilFrys
,q2.TotKvantTilFrys
,ISNULL(q1.EksternKommentar1,q2.EksternKommentar1) EksternKommentar1
,q2.[Last Upsert]
FROM (
SELECT w700.accountid
,w700.klientnr
,w700.tilgangstype
,w700.tilgangsnr
,w700.dato
,w700.Ankomstdato
,w700.LevNr
,w700.pakkemerke
,w789.VareANr
,sum(IIF(w789.prognosetype = 1, w789.Antall, NULL)) AS Antall1
,sum(IIF(w789.prognosetype = 1, w789.totkvant, NULL)) AS totkvant1
,sum(IIF(w789.prognosetype = 2, w789.Antall, NULL)) AS Antall2
,sum(IIF(w789.prognosetype = 2, w789.totkvant, NULL)) AS totkvant2
,w700.EksternKommentar1
FROM trading.W789Prognosekjopstat AS w789
INNER JOIN trading.W700Tilgangshode AS w700 ON w700.AccountId = w789.AccountId
AND w700.KlientNr = w789.Klientnr
AND w700.Tilgangsnr = w789.Tilgangsnr
AND w700.Tilgangstype = w789.Tilgangstype
AND w700.IsDeleted = 0
WHERE w789.IsDeleted = 0
GROUP BY w700.accountid
,w700.klientnr
,w700.tilgangstype
,w700.tilgangsnr
,w700.dato
,w700.Ankomstdato
,w700.LevNr
,w700.pakkemerke
,w789.VareANr
,w700.EksternKommentar1
) q1
FULL OUTER JOIN (
SELECT w700.accountid
,w700.klientnr
,w700.tilgangstype
,w700.tilgangsnr
,w700.dato
,w700.Ankomstdato
,w700.LevNr
,w700.pakkemerke
,w702.VareANr
,w702.Antall
,w702.TotKvant
,w702.ValPris
,w702.AntallTilFrys
,w702.TotKvantTilFrys
,w700.EksternKommentar1
,(SELECT MAX(LastUpdateDate) FROM (VALUES (w702.createdAt),(w702.updatedAt)) AS UpdateDate(LastUpdateDate)) AS 'Last Upsert'
FROM trading.w702PrognoseKjop w702
INNER JOIN trading.W700Tilgangshode AS w700 ON w700.AccountId = w702.AccountId
AND w700.KlientNr = w702.Klientnr
AND w700.Tilgangsnr = w702.Tilgangsnr
AND w700.Tilgangstype = w702.Tilgangstype
AND w700.IsDeleted = 0
WHERE w702.IsDeleted = 0
) q2 ON q1.accountid = q2.accountid
AND q1.klientnr = q2.klientnr
AND q1.tilgangstype = q2.tilgangstype
AND q1.tilgangsnr = q2.tilgangsnr
AND q1.vareanr = q2.vareanr
WHERE totkvant1 IS NOT NULL
OR totkvant2 IS NOT NULL
OR totkvant IS NOT NULL
Filtering with full join is really tricky. Your where criteria are actually turning the full join into a left join.
You can do what you want by filtering before the join:
select a.klientnr, a.uttakstype, a.uttaksnr, a.vareanr a.tableAitem,
b.vareanr b.tableBitem, a.kvantum a.tableAquantity, b.totkvant b.tableBquantity
from (select a.*
from tableA a
where a.UttaksNr = 639779 and a.IsDeleted = 0
) a full join
(select b.*
from tableB b
where b.IsDeleted = 0
) b
on a.klientnr = b.klientnr and
a.uttakstype= b.uttakstype and
a.uttaksnr = b.uttaksnr and
a.vareanr = b.vareanr;

MS SQL Conditional Join

I have a SQL Query :
SELECT * FROM Customer c
LEFT JOIN Invoice I ON I.InvcNum = C.Cust_InvcNum
some thing changed and the join does not work because there is no consistency in the data in the 'Cust_InvcNum'. So now when it does not find the record for the join or if it is null it needs to check for another condition.
LEFT JOIN Invoice I ON I.InvcNum = (SELECT p.InvcPrefix FROM Prefix WHERE p.DealerID = I.DealrID ) + '-' + I.InvcNum
second join I do works but it is taking too long for it get me data. Is there any other way to do this.
Earlier it used to be
Join on I.InvcNum = C.Cust_InvcNum
both the columns has the same data like DlrCd-InvcNum i.e both the columns 1234-A789
but not it could match on the above data or now the column 'InvcNum' in invoice table
can be populated like Dlrd-InvcNum or InvcPrefix-InvcNum
So InvcNum = 1234-A789 but CustNum = I94-A789
so we need to check if the for InvoicePrefix-InvcNum
SELECT *
FROM Customer c
LEFT JOIN (
SELECT i.InvcNum, p.InvcPrefix + '-' + I.InvcNum AS pInvcNum
FROM Invoice i LEFT JOIN Prefix p ON i.DealrID = p.DealrID
) ip ON c.Cust_InvcNum = CASE WHEN c.Cust_InvcNum = ip.InvcNum
THEN ip.InvcNum
ELSE ip.pInvcNum END

Need help on SELECT DISTINCT query

I'm using Firebird 2.1 to perform this query:
SELECT DISTINCT INVOICES.INVNO,INVOICES.DEPNO,INVOICES.INVN,INVOICES.CONTNO,SYSPROF.NAME
FROM INVOICES
LEFT JOIN INVSPEC ON (INVOICES.INVNO = INVSPEC.INVNO) AND (INVOICES.DEPNO = INVSPEC.DEPNO)
LEFT JOIN SYSPROF ON (INVSPEC.SYSNO = SYSPROF.SYSNO) WHERE
(INVOICES.INVNO = 17 AND INVOICES.DEPNO = 6555)
OR(INVOICES.INVNO = 16 AND INVOICES.DEPNO = 6555);
and it returns me these records:
Please help me to build a query that will return these records:
Thank you!
For instance:
SELECT INVOICES.INVNO,min(INVOICES.DEPNO),min(INVOICES.INVN),min(INVOICES.CONTNO),min(SYSPROF.NAME)
FROM INVOICES
LEFT JOIN INVSPEC ON (INVOICES.INVNO = INVSPEC.INVNO) AND (INVOICES.DEPNO = INVSPEC.DEPNO)
LEFT JOIN SYSPROF ON (INVSPEC.SYSNO = SYSPROF.SYSNO) WHERE
(INVOICES.INVNO = 17 AND INVOICES.DEPNO = 6555)
OR(INVOICES.INVNO = 16 AND INVOICES.DEPNO = 6555);
GROUP BY INVOICES.INVNO
This query returns one row per invoice and takes any name from the sysprof.