如何在最小月份获得MAX Hike?

时间:2019-05-07 07:40:27

标签: sql sql-server

下面是表格:

Name |  Hike%  |  Month
------------------------
A         7         1 
A         6         2
A         8         3
b         4         1
b         7         2
b         7         3

结果应为:

Name |  Hike%  |  Month
------------------------
A         8         3
b         7         2

3 个答案:

答案 0 :(得分:2)

这里是执行此操作的一种方法:

SELECT Name, [Hike%], Month
FROM
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY [Hike%] DESC, Month) rn
    FROM yourTable
) t
WHERE rn = 1
ORDER BY Name;

如果您想按名称返回多个记录,则在两个或两个以上记录因具有最大的加息百分比而并列的情况下,请将ROW_NUMBER替换为RANK

答案 1 :(得分:0)

使用相关子查询

select   Name,min(Hike) as Hike,min(Month) as Month  
from
(
   select * from tablename a
        where Hike in (select max(Hike) from tablename b where a.name=b.name)
)A group by Name

答案 2 :(得分:0)

您可以使用类似于以下内容的东西:

SELECT Name, MAX(Hike), Month
FROM table
GROUP BY Name, Month

希望这会有所帮助:)