如何从表

时间:2016-10-24 04:43:58

标签: sql oracle date greatest-n-per-group

我有一张表格,其中存储了交货日期和订单号。

在这里,我能够获得最大交货日期的订单。

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,但我的日期错误

7 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

您可以尝试此查询:

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。

答案 3 :(得分:0)

example.com/blog/posts/1

答案 4 :(得分:0)

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;

答案 5 :(得分:0)

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

 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)

答案 6 :(得分:-2)

更改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)