SQL:如何从表中获取最大值

时间:2014-11-17 05:50:21

标签: sql

enter image description here  值来自TABLE contracttenantproperty 那么我想根据每个idproperty得到max(expiry_date) 输出如:

idproperty| property_unit | tenant| expiry_date | idcontract   
 426      |  Car Park     | NGUY  | 2016-05-27  |   1578    
 432      | 13TH FLoor    | wong  | 2015-09-21  |   1455    
 433      | 14TH floor    | HA    | 2016-07-01  |   1629

感谢您的帮助!!

1 个答案:

答案 0 :(得分:1)

试试这个。使用OVER PARTITION BY查找每个property_unit的max expire_date

SELECT idproperty,
       property_unit,
       tenant,
       expiry_date,
       idcontract
FROM  (SELECT Row_number() OVER (partition BY idproperty, property_unit
                  ORDER BY expiry_date DESC) Rn,
              *
       FROM   tablename) a
WHERE  a.rn = 1