获取具有不同键的max(列)的行

时间:2013-09-08 08:02:39

标签: sql sql-server-2008

我有一些像

这样的数据
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查询?

3 个答案:

答案 0 :(得分:2)

您可以将ranking function 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

答案 1 :(得分: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

答案 2 :(得分: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