如何用MAX(列值)选择行?

时间:2016-02-26 17:24:35

标签: sql

我的表

ODR_NBR |   Snbr12      |   appot_nbr      | Creatins_ts
1       |   4001        |   2458           | 11/24/2015 4:38:00 PM
1       |   4001        |   2458           | 11/22/2015 4:50:00 PM
2       |   4005        |   3598           | 11/27/2015 4:38:00 PM
2       |   4005        |   3598           | 11/24/2015 4:20:00 PM

我的表在sql之后

ODR_NBR |   Snbr12      | Creatins_ts
1       |   4001        |  11/24/2015 4:38:00 PM
2       |   4005        |  11/27/2015 4:38:00 PM

2 个答案:

答案 0 :(得分:2)

这可以为您提供所需的结果:

示例数据:

CREATE TABLE table1 (ODR_NBR int ,  Snbr12     int ,  appot_nbr    int   ,Creatins_ts datetime)

 INSERT INTO table1
 VALUES
    (1       ,  4001        ,  2458           ,'11/24/2015 4:38:00 PM'),
    (1       ,  4001        ,  2458           ,'11/22/2015 4:50:00 PM'),
    (2       ,  4005        ,  3598           ,'11/27/2015 4:38:00 PM'),
    (2       ,  4005        ,  3598           ,'11/24/2015 4:20:00 PM')

查询:

    SELECT ODR_NBR ,  Snbr12  ,  MAX(Creatins_ts) AS Creatins_ts 
    FROM table1 
    GROUP BY ODR_NBR ,  Snbr12   

结果:

enter image description here

答案 1 :(得分:0)

希望这会有所帮助

SELECT t1.ODR_NBR, t1.Snbr12, t1.Creatins_ts 
FROM mytable t1 JOIN mytable t2 
    ON t1.ODR_NBR=t2.ODR_NBR
WHERE t1.Creatins_ts > t2.Creatins_ts