![](/img/trans.png)
[英]SQL Query to Get Max Value Based on Different Max Value Given Multiple Records
[英]SQL - Query MAX value given MAX value of different column
我的表有三列[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和该年份的最大MALES值。 因此,以上示例的结果将是:
[ID] [YEAR] [MALES]
1 2012 25
2 2012 10
您要使用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;
;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
您需要使用子查询来获取最大年份,然后加入该查询以获取该年份的最大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
如果我了解您想要的内容(您的措词有些困难,但是该示例使您看起来像我想要第二个)。
每个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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.