SQL - 查询MAX值给定不同列的MAX值

时间:2013-08-01 17:58:14

标签: sql sql-server tsql

我的表有三列[ID], [YEAR], [MALES],对于任何给定的ID,多个YEAR值可以有多个MALES值。

EX。

[ID]     [YEAR]     [MALES]
1        2010       10
1        2011       20
1        2011       35
1        2011       0
1        2012       25
1        2012       10
2        2010       5
2        2011       2
2        2011       11
2        2011       12
2        2012       0
2        2012       10

我需要查询每个ID的YEAR的最大YEAR和最大MALES值。所以上面例子的结果是:

[ID]     [YEAR]     [MALES]
1        2012       25
2        2012       10

4 个答案:

答案 0 :(得分:2)

您希望使用row_number()

执行此操作
select id, year, males
from (select t.*,
             row_number() over (partition by id
                                order by years desc, males desc
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

答案 1 :(得分:0)

;with CTE as
(
    select
        *,
        row_number() over (partition by ID order by year desc, males desc) as row_num
    from table
)
select *
from CTE
where row_num = 1

;with CTE as
(
    select ID, max(Year) as Year
    from table
    group by ID
)
select t.ID, t.Year, max(males) as males
from table as t
    inner join CTE as c on c.ID = t.ID and c.Year = t.Year
group by t.ID, t.year

答案 2 :(得分:0)

您需要使用子查询来获取最大年份,然后加入到该年份以获得该年度的最大MALES。

SELECT  T.ID
        ,SQ.MAX_YEAR
        ,MAX(T.MALES)
FROM    TABLE1 T
INNER JOIN
        (
        SELECT  ID
                ,MAX(YEAR) AS MAX_YEAR
        FROM    TABLE1 
        GROUP BY
                ID
        ) SQ
ON      T.ID = SQ.ID
AND     T.YEAR = SQ.MAX_YEAR
GROUP BY
        T.ID
        ,SQ.MAX_YEAR

答案 3 :(得分:0)

如果我理解你想要的东西(你的写法有些困难,但是这个例子让你看起来像是你想要的第二个)。

每个ID的最大年份:

SELECT id, MAX(year) FROM data;

每个最大年份ID的最大男性数:

SELECT id, year, MAX(males) FROM data WHERE year = (SELECT MAX(year) FROM data) 
    GROUP BY id;