有一个带有pcode的表,其中包含许多不同行的日期。如何仅选择pcode的最新日期

时间:2016-08-22 05:58:46

标签: sql postgresql

表的图像在以下链接中。

enter image description here

4 个答案:

答案 0 :(得分:0)

一种方法是使用rank窗口函数:

SELECT pcode, 
       prodate
FROM   (SELECT pcode, 
               prodate, 
               RANK() OVER (PARTITION BY pcode ORDER BY prodate DESC) rk
        FROM   mytable)
WHERE  rk = 1

答案 1 :(得分:0)

select t1.pcode, t2.max_date
from table1 t1
inner join
(
  select max(prodate) max_date, pcode
  from table1
  group by pcode
) t2
  on t1.pcode= t2.pcode
  and t1.prodate = t2.max_date

答案 2 :(得分:0)

select max(prodate) from mytable
group by pcode

答案 3 :(得分:0)

使用 Row_Number()分区依据

SELECT X.pcode, 
       X.prodate
FROM   (SELECT pcode, 
               prodate, 
               Row_Number() OVER (PARTITION BY pcode ORDER BY prodate DESC) PartNo
        FROM  table) X
WHERE  X.PartNo = 1