如何在持续时间 mysql 中从 1 获取两行?

How can i get two row from 1 in duration mysql?

我有这样的行:

编号,start_date,end_date
0、2000-01-01 20:00:00、2000-01-01 21:00:00
1, 2000-01-01 23:00:00, 2000-01-02 04:00:00

我需要得到如下报告结果:

日期 | time_online
2000-01-01 | 02:00:00
2000-01-02 | 04:00:00

我的解决方案是错误的,因为我只有 start_date 个计数。

SELECT DATE_FORMAT(start_date, '%Y-%m-%d') as date, 
SUM(CASE WHEN EXTRACT(DAY FROM start_date) <> EXTRACT(DAY FROM end_date) 
THEN  
    TIMESTAMPDIFF(SECOND, start_date, DATE_FORMAT(start_date + INTERVAL 1 DAY, '%Y-%m-%d')) 
ELSE 
    TIMESTAMPDIFF(SECOND, start_date, end_date) END) time_online
FROM online
GROUP BY date

结果:

日期 | time_online
2000-01-01 | 02:00:00

有人可以帮助我吗?

您需要的是一个(虚拟)参考 table,在线 table 中每个日期的时间跨度为 24 小时。 您可以使用 table 本身来做到这一点:

SELECT
    DATE(start_date) + INTERVAL 0 HOUR ref_start,
    DATE(start_date) + INTERVAL 24 HOUR ref_end
FROM
    online
WHERE
    end_date IS NOT NULL
UNION DISTINCT
SELECT
    DATE(end_date) + INTERVAL 0 HOUR ref_start,
    DATE(end_date) + INTERVAL 24 HOUR ref_end
FROM
    online
WHERE
    end_date IS NOT NULL

+ INTERVAL 0 HOUR 并不是真正必要的,为了清楚起见,我补充说,DISTINCT 关键字也是如此。

如果你把它放在子查询中,那么你可以通过(某种)自连接重叠的记录,并根据值计算差异:

SELECT 
    DATE(r.ref_start) ref_date,
    SEC_TO_TIME(SUM(TIMESTAMPDIFF(SECOND,
        CASE WHEN d.start_date >= r.ref_start
            THEN d.start_date
            ELSE r.ref_start
        END,
        CASE WHEN d.end_date <= r.ref_end
            THEN d.end_date
            ELSE r.ref_end
        END))) time_online
FROM
    (
    SELECT
        DATE(start_date) + INTERVAL 0 HOUR ref_start,
        DATE(start_date) + INTERVAL 24 HOUR ref_end
    FROM
        online
    WHERE
        end_date IS NOT NULL
    UNION DISTINCT
    SELECT
        DATE(end_date) + INTERVAL 0 HOUR ref_start,
        DATE(end_date) + INTERVAL 24 HOUR ref_end
    FROM
        online
    WHERE
        end_date IS NOT NULL
    ) r
JOIN
    online d
    ON d.end_date > r.ref_start
    AND d.start_date < r.ref_end
GROUP BY ref_date