1

I am doing a query that looks at each part transaction within a certain time period. Depending on the part, it could have maybe just 1 transaction or upwards of 1000 transactions. I need to only pull the last 5 transactions per part. Here is my query right without selecting only the last 5 transactions per part.

 SELECT     partnum, trandate, extcost
 FROM       parttran
 WHERE      trandate between '2012-05-15' and '2013-05-14'

I greatly appreciate your help!

4

1 回答 1

2

在这些情况下总是有用的:具有如下窗口函数的CTEROW_NUMBER

WITH CTE AS
(
    SELECT  partnum, trandate, extcost,
            rn = ROW_NUMBER() OVER (PARTITION BY partnum ORDER BY trandate DESC)
    FROM    parttran
    WHERE   trandate between '2012-05-15' and '2013-05-14'
)
SELECT partnum, trandate, extcost FROM CTE WHERE rn <= 5
于 2013-05-17T13:44:04.293 回答