You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求编写SQL查询:计算ECOM_DATA表订单7658状态15到20的天数差

Calculate Days Between Status Changes for Order 7658

Hey there! Let's break down how to get the number of days between when order 7658 switched from status 15 to status 20.

Approach

The core idea is simple:

  • Grab the activity date of the record where the order is in status 15
  • Grab the activity date of the record where the order is in status 20
  • Calculate the difference between these two dates

Basic SQL Query (Works for Most Databases)

Since your sample data only has one entry per status for the order, here's a straightforward self-join query:

-- For Oracle (using native date subtraction)
SELECT 
    (TRUNC(stat20.STAT_DATE_ACT) - TRUNC(stat15.STAT_DATE_ACT)) AS days_between_status_change
FROM 
    ECOM_DATA stat15
INNER JOIN 
    ECOM_DATA stat20 
    ON stat15.ORD_NO = stat20.ORD_NO
WHERE 
    stat15.ORD_NO = 7658
    AND stat15.INT_ORD_LINE_STAT_EXP = 15
    AND stat20.INT_ORD_LINE_STAT_EXP = 20;

If you're using MySQL, swap in the DATEDIFF function:

-- For MySQL
SELECT 
    DATEDIFF(stat20.STAT_DATE_ACT, stat15.STAT_DATE_ACT) AS days_between_status_change
FROM 
    ECOM_DATA stat15
INNER JOIN 
    ECOM_DATA stat20 
    ON stat15.ORD_NO = stat20.ORD_NO
WHERE 
    stat15.ORD_NO = 7658
    AND stat15.INT_ORD_LINE_STAT_EXP = 15
    AND stat20.INT_ORD_LINE_STAT_EXP = 20;

Handling Multiple Entries for the Same Status

If your table might have duplicate status entries (e.g., the order was reverted to status 15 before moving to 20), adjust the query to pick the most recent status 15 date and the first status 20 date that follows it:

-- Oracle example with aggregation
SELECT 
    (TRUNC(stat20.first_status_20_date) - TRUNC(stat15.last_status_15_date)) AS days_between_status_change
FROM 
    (
        SELECT 
            ORD_NO, 
            MAX(STAT_DATE_ACT) AS last_status_15_date
        FROM ECOM_DATA
        WHERE ORD_NO = 7658 AND INT_ORD_LINE_STAT_EXP = 15
        GROUP BY ORD_NO
    ) stat15
INNER JOIN 
    (
        SELECT 
            ORD_NO, 
            MIN(STAT_DATE_ACT) AS first_status_20_date
        FROM ECOM_DATA
        WHERE ORD_NO = 7658 AND INT_ORD_LINE_STAT_EXP = 20
        GROUP BY ORD_NO
    ) stat20 
    ON stat15.ORD_NO = stat20.ORD_NO;

Expected Result

For your sample data, all these queries will return 5—the exact number of days between 11-OCT-17 and 16-OCT-17.

内容的提问来源于stack exchange,提问作者R Srini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:21:06