需要选择最后

时间:2016-09-06 00:46:12

标签: sql sql-server-2008 row-number

--------------------------------------------------------------
AnimalName  AnimalType  RowNumber   
---------------------------------------------------------------
Chicken         Bird        1   
Duck            Bird        2       
Alpaca          Mammal      1   
Camel           Mammal      2   
Carabao         Mammal      3   
Whale           Sea         1   
Shark           sea         2   
Prawns          Sea         3   
Eel             sea         4   

输出

AnimalName      AnimalType  RowNumber   
------------------------------------------------------------        
Duck              Bird          2   
Carabao           Mammal        3   
Eel               sea           4   

查询:

  SELECT t.* from (
select  
    AnimalName,
    AnimalType,
    ROW_NUMBER() OVER(PARTITION BY AnimalType ORDER BY AnimalName) AS RowNumber
FROM    Animal A
) t
where rownumber=1

上面的查询给了我所有的第一个rownumber,如果我想选择最后一个rownumber,那么我必须做出什么改变。 例如:bird max rownumber为2,哺乳动物max为3,sea max为4

1 个答案:

答案 0 :(得分:2)

只需使用DESC代替ASC ORDER BY

SELECT a.* 
FROM (SELECT AnimalName, AnimalType,
             ROW_NUMBER() OVER (PARTITION BY AnimalType ORDER BY AnimalName DESC) AS RowNumber
      FROM Animal a
     ) a
WHERE rownumber = 1;

如果您确实要保留行号,请使用COUNT(*)进行比较:

SELECT a.AnimalName, a.AnimalType, a.rownumber
FROM (SELECT AnimalName, AnimalType,
             ROW_NUMBER() OVER (PARTITION BY AnimalType ORDER BY AnimalName) AS RowNumber,
             COUNT(*) OVER (PARTITION BY AnimalType) as cnt
      FROM Animal a
     ) a
WHERE rownumber = cnt;