How to find N Consecutive records in a table using SQL

前端 未结 4 960
Happy的楠姐
Happy的楠姐 2020-12-30 12:16

I have the following Table definition with sample data. In the following table, Customer Product & Date are key fields

Table One
Customer   Product    Da         


        
4条回答
  •  说谎
    说谎 (楼主)
    2020-12-30 12:53

    A different approach, inspired by munchs last line.

    Get - for a given date the first date with YES later than that, and the last date with YES earlier than that. These form the boundary, where our dates shall fit in.

    SELECT (o1.datum),
        MAX (o3.datum) - MIN (o2.datum) AS diff
    FROM one o1, one o2, one o3 
    WHERE o1.sale = 'NO'
    AND o3.datum <
        (SELECT MIN (datum) 
        FROM one 
        WHERE datum >= o1.datum 
        AND SALE = 'YES') 
    AND o2.datum > 
        (SELECT MAX (datum) 
        FROM one 
        WHERE datum <= o1.datum 
        AND SALE = 'YES') 
    GROUP BY o1.datum 
    HAVING MAX (o3.datum) - MIN (o2.datum) >= 2
    ORDER BY o1.datum;
    

    Maybe it needs some kind of optimization, because table one is 5 times involved in the query. :)

提交回复
热议问题