Oracle SQL自上一个订单以来已经过了多少天

9rygscc1  于 2022-11-03  发布在  Oracle
关注(0)|答案(2)|浏览(102)

我有一个问题,如何计算的日子有多少天已经过去了,因为以前的订单。
我的代码:

select
    order_id,
    order_date
from 
    oe.orders
where customer_id = 838
order by
    order_date desc

订单标识和订单日期如下所示:
1.订单标识= 1920 &订单日期= 2019年3月2515.45.38.000000000
1.订单标识= 1618和订单日期= 2019年12.51.39.000000000
1.公司性质:外商独资公司规模:2000 - 3 - 1007.35.46.000000000
我是sql的新用户,不知道怎么做。谢谢你的帮助!

0lvr5msh

0lvr5msh1#

如果您要以天数表示差异(仅日期部分),则:

WITH
    tbl AS
        (
            Select 1 "ID", To_Date('25-MAR-19 15.45.38', 'dd-MON-yy hh24:mi:ss') "A_DATE" From Dual Union All
            Select 2 "ID", To_Date('08-FEB-19 12.51.39', 'dd-MON-yy hh24:mi:ss') "A_DATE" From Dual Union All
            Select 3 "ID", To_Date('04-FEB-19 07.35.46', 'dd-MON-yy hh24:mi:ss') "A_DATE" From Dual Union All
            Select 4 "ID", To_Date('28-JAN-19 12.13.10', 'dd-MON-yy hh24:mi:ss') "A_DATE" From Dual 
        )

Select
    ID "ID",
    TRUNC(A_DATE, 'dd') - TRUNC(Nvl(First_Value(A_DATE) OVER (Order By ID Rows Between 1 Preceding And Current Row), A_DATE), 'dd') "DAYS_DIFF"
From
    tbl

| 识别码|天数_差异|
| - -|- -|
| 一个|第0页|
| 2个|-45个|
| 三个|-4个|
| 四个|-7天|
或者......

Select
    ID "ID",
    TRUNC(A_DATE, 'dd') - TRUNC(Nvl(Last_Value(A_DATE) OVER (Order By ID Rows Between Current Row And 1 Following ), A_DATE), 'dd') "DAYS_DIFF"
From
    tbl
Order By TRUNC(A_DATE, 'dd')

...结果
| 识别码|天数_差异|
| - -|- -|
| 四个|第0页|
| 三个|七个|
| 2个|四个|
| 一个|四十五|
此致

ncgqoxb0

ncgqoxb02#

CREATE TABLE orders
(ORDER_ID, ORDER_DATE) AS
SELECT 3,  TIMESTAMP'2022-10-31 09:54:48' FROM DUAL UNION ALL
SELECT 2,  TIMESTAMP'2022-10-17 19:04:44' FROM DUAL UNION ALL
SELECT 1,  TIMESTAMP'2022-10-08 14:44:23' FROM DUAL 

SELECT order_id, order_date,
order_date - LAG(order_date) OVER (ORDER BY order_id) AS diff
FROM   orders;

ORDER_ID    ORDER_DATE    DIFF
1    08-OCT-22 02.44.23.000000 PM     - 
2    17-OCT-22 07.04.44.000000 PM    +000000009 04:20:21.000000000
3    31-OCT-22 09.54.48.000000 AM    +000000013 14:50:04.000000000

相关问题