Reputation: 85
SELECT TOP (100) PERCENT dbo.vwLatestEquipment.equipServID, dbo.tblEquipInvoice.invoiceDateSent, dbo.tblEquipment.equipManafacturer,
dbo.tblEquipInvoice.contractNumber, dbo.tblEquipment.equipmentID, dbo.tblEquipment.equipStatus, dbo.tbl_work_locations.work_location,
dbo.vwLatestEquipment.calibDueDate
FROM dbo.vwLatestEquipment INNER JOIN
dbo.tblEquipLocations ON dbo.vwLatestEquipment.locationID = dbo.tblEquipLocations.locationID INNER JOIN
dbo.tblEquipInvoice ON dbo.tblEquipLocations.invoiceID = dbo.tblEquipInvoice.invoiceID INNER JOIN
dbo.tblEquipment ON dbo.vwLatestEquipment.equipServID = dbo.tblEquipment.equipServID INNER JOIN
dbo.tbl_work_locations ON dbo.tblEquipInvoice.workLocationID = dbo.tbl_work_locations.work_id
GROUP BY dbo.tbl_work_locations.work_location, dbo.vwLatestEquipment.equipServID, dbo.tblEquipInvoice.invoiceDateSent, dbo.tblEquipment.equipManafacturer,
dbo.tblEquipInvoice.contractNumber, dbo.tblEquipment.equipmentID, dbo.tblEquipment.equipStatus, dbo.tbl_work_locations.work_location,
dbo.vwLatestEquipment.calibDueDate
ORDER BY dbo.vwLatestEquipment.equipServID
This is one that's been passed to me from my successor, the view above is working fine for purpose, except it returns all the values for calibDateDue for every item of equipmentID All I want is for it to return the most recent calibDueDate for each item of equipment (equipmentID) any help would be appreciated today as I am fried and cant make much headway.
Upvotes: 2
Views: 92
Reputation: 79959
I want is for it to return the most recent calibDueDate for each item of equipment (equipmentID).
Since you are using TOP (100) PERCENT
, I will assume that you are using SQL Server. Then you can use the ranking function:
ROW_NUMBER() OVER(PARTITION BY equipmentID
ORDER BY calibDueDate DESC)
Then select only the row with the rank = 1, like so:
;WITH CTE
AS
(
SELECT
dbo.vwLatestEquipment.equipServID,
dbo.tblEquipInvoice.invoiceDateSent,
dbo.tblEquipment.equipManafacturer,
dbo.tblEquipInvoice.contractNumber,
dbo.tblEquipment.equipmentID,
dbo.tblEquipment.equipStatus,
dbo.tbl_work_locations.work_location,
dbo.vwLatestEquipment.calibDueDate,
ROW_NUMBER() OVER(PARTITION BY equipmentID
ORDER BY calibDueDate DESC) row_num
FROM dbo.vwLatestEquipment
INNER JOIN dbo.tblEquipLocations
ON dbo.vwLatestEquipment.locationID=dbo.tblEquipLocations.locationID
INNER JOIN dbo.tblEquipInvoice
ON dbo.tblEquipLocations.invoiceID=dbo.tblEquipInvoice.invoiceID
INNER JOIN dbo.tblEquipment
ON dbo.vwLatestEquipment.equipServID=dbo.tblEquipment.equipServID
INNER JOIN dbo.tbl_work_locations
ON dbo.tblEquipInvoice.workLocationID=dbo.tbl_work_locations.work_id
)
SELECT TOP (100) PERCENT *
FROM CTE
WHERE row_num = 1
ORDER BY equipServID;
Upvotes: 1