Home  >  Q&A  >  body text

How to get the first wire_open and wire_close group in the data

This is the data I want to output, it matches the blue line and the photo of the desired output I have attached, please take a look and use the SQL query to get the desired result

P粉317679342P粉317679342236 days ago333

reply all(1)I'll reply

  • P粉571233520

    P粉5712335202024-02-27 07:08:07

    测试一下:

    WITH
    cte AS (
        SELECT *, SUM(delay_ping_type = 'wire_close') OVER (ORDER BY last_updated_on DESC) group_no
        FROM source_table
    )
    SELECT MIN(last_updated_on) wire_open, 
           MAX(last_updated_on) wire_close 
    FROM cte
    -- WHERE group_no > 0   -- removes final open without close
    GROUP BY group_no
    -- HAVING wire_open < wire_close  -- removes close without matched open
    -- HAVING MIN(last_updated_on) < MAX(last_updated_on) -- the same for PostgreSQL
    ;
    

    https://www.db-fiddle.com/f/njuPYFYug87jTWKHHv6yRK/2 (感谢 @lemon 的小提琴)。

    reply
    0
  • Cancelreply