搜尋

首頁  >  問答  >  主體

基於起始時間和結束時間的資料進行小時計數

<p>在表格中,資料以時間戳記格式存在,但我以時間(start_at)和時間(end_at)的格式共享它。 </p> <p>表格結構:</p> <pre class="brush:php;toolbar:false;">id, start_at, end_at 1, 03:00:00, 06:00:00 2, 02:00:00, 05:00:00 3, 01:00:00, 08:00:00 4, 08:00:00, 13:00:00 5, 09:00:00, 21:00:00 6, 13:00:00, 16:00:00 6, 15:00:00, 19:00:00</pre> <p>對於結果,我們需要計算在start_at和end_at時間之間活動的id數量。 </p> <pre class="brush:php;toolbar:false;">hours, count 0, 0 1, 1 2, 2 3, 3 4, 3 5, 2 6, 1 7, 1 8, 1 9, 2 10, 2 11, 2 12, 2 13, 3 14, 2 15, 3 16, 2 17, 2 18, 2 19, 1 20, 1 21, 0 22, 0 23, 0</pre></p>
P粉283559033P粉283559033450 天前448

全部回覆(1)我來回復

  • P粉432930081

    P粉4329300812023-08-31 09:26:55

    要么

    WITH RECURSIVE
    cte AS (
        SELECT 0 `hour`
        UNION ALL
        SELECT `hour` + 1 FROM cte WHERE `hour` < 23
    )
    SELECT cte.`hour`, COUNT(test.id) `count`
    FROM cte 
    LEFT JOIN test ON cte.`hour` >= HOUR(test.start_at)
                  AND cte.`hour` < HOUR(test.end_at)
    GROUP BY 1
    ORDER BY 1;
    

    要么

    WITH RECURSIVE
    cte AS (
        SELECT CAST('00:00:00' AS TIME) `hour`
        UNION ALL
        SELECT `hour` + INTERVAL 1 HOUR FROM cte WHERE `hour` < '23:00:00'
    )
    SELECT cte.`hour`, COUNT(test.id) `count`
    FROM cte 
    LEFT JOIN test ON cte.`hour` >= test.start_at 
                  AND cte.`hour` < test.end_at 
    GROUP BY 1
    ORDER BY 1;
    

    第一個查詢以時間格式傳回小時列,而第二個查詢以數值形式傳回此列。選擇對您來說安全的變體。

    https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5a77b6e3158be06c7a551cb7e64673de

    #

    回覆
    0
  • 取消回覆