2
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

这是我的继任者传给我的,上面的视图可以正常工作,除了它为设备ID的每个项目返回calibDateDue的所有值我想要的是它返回每个项目的最新calibDueDate设备 (equipmentID) 今天任何帮助都将不胜感激,因为我很受煎熬,无法取得太大进展。

4

1 回答 1

1

我想要的是它为每件设备(设备ID)返回最新的calibDueDate。

由于您使用的是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;
于 2012-12-04T10:33:45.167 回答