0

我有一些数据,比如

code    amount  month
aaa1    100     1
aaa1    200     2
aaa1    300     3
aaa4    450     2
aaa4    400     3
aaa6    0       2

从上面,对于每个代码,我想获取带有 max(month) 的行

code    amount  month
aaa1    300     3
aaa4    400     3
aaa6    0       2

如何为此创建一个 ms sql 查询?

4

3 回答 3

2

您可以使用排名函数 ROW_NUMBER()PARTITION BY code ORDER BY month DESC执行此操作:

WITH CTE
AS
(
   SELECT 
     code, amount, month,
     ROW_NUMBER() OVER(PARTITION BY code 
                       ORDER BY month DESC) AS RN
   FROM Tablename
)
SELECT code, amount, month
FROM CTE
WHERE RN = 1;

这将为您month提供每个code.

于 2013-09-08T08:03:58.647 回答
2
;WITH MyCTE AS
(
    SELECT code,
           amount,
           month,
           ROW_NUMBER() OVER(PARTITION BY code ORDER BY code,month DESC) AS rownum
    FROM   table
)
SELECT *
FROM   MyCTE 
WHERE  rownum = 1
于 2013-09-08T08:05:44.513 回答
1

试试这个

SELECT * 
FROM 
  (SELECT MAX(MONTH) month, code
  FROM table1
  GROUP BY code) res
JOIN table1
ON res.month = table1.month 
AND res.code = table1.code

这是SQLfiddle

于 2013-09-08T08:33:52.613 回答