1

我需要得到最后 QuoteDate 的价格。

现在我有这样的查询

SELECT      dbo.INMT.Material, dbo.INMT.LastVendor, dbo.INMT.AvgCost, dbo.MSQD.Status, dbo.MSQH.QuoteDate, dbo.MSQD.UnitPrice
FROM         dbo.INMT INNER JOIN
                      dbo.MSQD ON dbo.INMT.MatlGroup = dbo.MSQD.MatlGroup AND dbo.INMT.Material = dbo.MSQD.Material INNER JOIN
                      dbo.MSQH ON dbo.MSQD.MSCo = dbo.MSQH.MSCo AND dbo.MSQD.Quote = dbo.MSQH.Quote
GROUP BY dbo.INMT.Material, dbo.INMT.LastVendor, dbo.INMT.AvgCost, dbo.MSQD.Status, dbo.MSQD.UnitPrice, dbo.MSQH.QuoteDate
ORDER BY dbo.INMT.Material

并得到以下结果

在此处输入图像描述

以及如何运行查询以获取突出显示的记录。我尝试执行类似 where QuoteDate =max ......但也许我的分组不正确。

谢谢

4

2 回答 2

4

因此,假设 SQL Server 2005+,您可以使用 a CTEROW_NUMBER()

;WITH CTE AS
(
    SELECT  I.Material, 
            I.LastVendor, 
            I.AvgCost, 
            MD.Status, 
            MH.QuoteDate, 
            MD.UnitPrice,
            RN = ROW_NUMBER() OVER( PARTITION BY I.Material, I.LastVendor, 
                                                 I.AvgCost, MD.Status, 
                                                 MD.UnitPrice
                                    ORDER BY MH.QuoteDate DESC)
    FROM dbo.INMT I
    INNER JOIN dbo.MSQD MD
        ON I.MatlGroup = MD.MatlGroup 
        AND I.Material = MD.Material 
    INNER JOIN dbo.MSQH MH
        ON MD.MSCo = MH.MSCo 
        AND MD.Quote = MH.Quote
)
SELECT  Material, 
        LastVendor, 
        AvgCost, 
        Status, 
        QuoteDate, 
        UnitPrice
FROM CTE
WHERE RN = 1
于 2013-06-10T14:29:47.587 回答
0

在 order by 子句之后使用 HAVING QuoteDate=max...。

于 2013-06-10T14:27:34.217 回答