Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select only the second max date from a table

I have a table where the delivery date and order number are stored.

Here i was able to get the order with the max delivery date.

SELECT DISTINCT D.ORDER_NO
FROM DELIVERY D
WHERE D.CUSTOMER_NO =112 AND D.DELIVERY_DATE = (SELECT  MAX(D1.DELIVERY_DATE) FROM DELIVERY D1
WHERE D1.CUSTOMER_NO = 112 );

Here a single customer may have multiple orders.

Now what i want is to get only the second max date.

By using the above query I was able to get the list of data other than the max delivery date by changing the = to < and adding ORDER BY in the subquery.

But its an entire list but i want only the second max date.

Someone pls tell me how I can get only the second max date.

Note: I have tried using ROWNUM<=1 but i am getting wrong date

like image 376
Tony Roczz Avatar asked Nov 16 '25 11:11

Tony Roczz


1 Answers

Assuming you are using Oracle:

SELECT *
FROM
(
    SELECT t.*, rownum rnum
    FROM
    (
        SELECT DISTINCT D.ORDER_NO
        FROM DELIVERY D
        WHERE D.CUSTOMER_NO = 112
        ORDER BY D.DELIVERY_DATE DESC
    ) t
    WHERE rownum <= 2
)
WHERE rnum >= 2
like image 185
Tim Biegeleisen Avatar answered Nov 19 '25 06:11

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!