oracle 如何从表中只选择第二个最大日期

xghobddn  于 2023-01-04  发布在  Oracle
关注(0)|答案(7)|浏览(191)

我有一个表,其中存储了交货日期和订单号。
在这里,我能够得到最大交货日期的订单。

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 );

这里一个客户可能有多个订单。
现在我想要的是只得到第二个最大日期。
通过使用上面的查询,我可以通过将=更改为<并在子查询中添加ORDER BY来获取除最大交付日期之外的数据列表。
但这是一个完整的名单,但我只想第二个最大的日期。
有人请告诉我,我怎么才能得到只有第二个最大的日期。
注意:我已经尝试使用ROWNUM<=1,但我得到了错误的日期

new9mtju

new9mtju1#

假设您使用的是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
htzpubme

htzpubme2#

SELECT * FROM(
SELECT DISTINCT D.ORDER_NO, ROW_NUMBER()OVER(order by D.DELIVERY_DATE desc) RowNo
FROM DELIVERY D
WHERE D.CUSTOMER_NO =112
) t where t.RowNo = 2
e3bfsja2

e3bfsja23#

您可以尝试以下查询:

SELECT DISTINCT ORDER_NO FROM DELIVERY WHERE CUSTOMER_NO=112 AND DELIVERY_DATE =
(SELECT MAX(DELIVERY_DATE) FROM DELIVERY WHERE CUSTOMER_NO=112 AND 
DELIVERY_DATE<(SELECT MAX(DELIVERY_DATE) FROM DELIVERY AND CUSTOMER_NO=112));

子查询将返回第二个最大交货日期,它将给出第二个最大日期的order_no。

u5i3ibmn

u5i3ibmn4#

从表中选择第二个最大日期

SELECT MAX(date) FROM tbl_date WHERE date NOT IN (SELECT MAX(date) FROM tbl_date )
        OR
        SELECT DISTINCT date FROM tbl_date  ORDER BY date DESC LIMIT 1,1;
        OR
        SELECT MAX(date) FROM ( SELECT date FROM tbl_date  MINUS SELECT MAX(date) FROM tbl_date)
zzzyeukh

zzzyeukh5#

SELECT TOP 1 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 );
 ORDER BY  DELIVERY_DATE  DESC
nlejzf6q

nlejzf6q6#

SELECT D.ORDER_NO
FROM
(
SELECT DISTINCT D.ORDER_NO,D.DELIVERY_DATE,ROW_NUMBER()OVER(order by D.DELIVERY_DATE desc) RowNo
FROM DELIVERY D
WHERE D.CUSTOMER_NO =1128158 
ORDER BY D.DELIVERY_DATE DESC)
t WHERE t.RowNo = 2;
ma8fv8wu

ma8fv8wu7#

更改D.DELIVERY_DATE =
D.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 );

或类似下面的东西

SELECT MAX(DELIVERY_DATE)
  FROM TABLE
 WHERE DELIVERY_DATE< ( SELECT MAX(DELIVERY_DATE)
                 FROM TABLE)

相关问题