2016-11-24 54 views
0

我想找出有通過產品的最大日起行,最大日期排PostgreSQL的

click to see table

我想的product_id

click here to see what i want

找出的最大行日期

我試過DISTINCT,但不能成功!

+2

http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557# 285557 –

+0

'select * from product p where not exists(select * from product x where x.product_id = p.product_id and x.pdate> p.pdate);' – joop

回答

0
select * from (
    SELECT *, row_number() over (partition by Product_ID order by date desc) r 
    FROM table 
) T 
WHERE T.r=1 
+0

很好的回答!它真的有幫助 –

+0

歡迎@RohanNayani如果它幫助你凸輪標記爲答案 – mohan111

1

這樣做的一個典型方法是使用子查詢來識別與每個產品ID的最大日期相對應的記錄,然後通過INNER JOIN限制原始表格。

SELECT t1.* 
FROM yourTable t1 
INNER JOIN 
(
    SELECT PRODUCT_ID, MAX(DATE) AS DATE 
    FROM yourTable 
    GROUP BY PRODUCT_ID 
) t2 
    ON t1.PRODUCT_ID = t2.PRODUCT_ID AND 
     t1.DATE  = t2.DATE 

另一種方法是通過窗口功能。

+0

非常感謝您的快速響應! –