从多个相似结果中选择单个记录

时间:2012-12-04 10:28:56

标签: sql asp-classic vbscript views

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

这是从我的继任者那里传递给我的,上面的视图工作正常,除了它为设备的每个项目返回所有的calibDateDue值所有我想要的是它返回最新的calibDueDate为每一项设备(设备ID)今天都会受到赞赏,因为我很油腻,不能取得很大的进展。

1 个答案:

答案 0 :(得分:1)

  

我想要它为每个项目返回最新的calibDueDate   设备(设备ID)。

由于您使用的是TOP (100) PERCENT,我将假设您使用的是SQL Server。然后你可以使用排名功能:

ROW_NUMBER() OVER(PARTITION BY equipmentID
                  ORDER BY calibDueDate DESC) 

然后只选择rank = 1的行,如下所示:

;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;