How to find N Consecutive records in a table using SQL

前端 未结 4 978
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 13:01

    Ok, we need a variable answer. We search for a date, where we have N following dates, all with the sale-field being NO.

    SELECT d1.datum
    FROM one d1, one d2, i 
    WHERE d1.sale = 'NO' AND d2.sale = 'NO'
      AND d1.datum = (d2.datum - i) 
      AND i > 0 AND i < 4 
    GROUP BY d1.datum 
    HAVING COUNT (*) = 3; 
    

    This will give us the date, which we use for subquerying.

    Notes:

    • I used 'datum' instead of date, because date is a reserved keyword on postgresql.

    • In Oracle you can use a virtual table dummy, which contains anything you ask for, like 'SELCT foo FROM dual WHERE foo in (1, 2, 3);' which will give you 1, 2, 3, if I remember correctly. Depending on the vendor, there might be other tricks to get a sequence 1 to N. I created a table i with column i, and filled it with the values 1 to 100, and I expect N not to exceed 100; Since a few versions, postgresql contains a function 'generate_series (from, to) which would solve the problem too, and might have similarities with solutions for your specific database. But table i should work vendor independent.

    • if N == 17, you have to modify 3 places from 3 to 17.

    The final query will be:

    SELECT o4.* 
    FROM one o3, one o4 
    WHERE o3.datum = (
        SELECT d1.datum
        FROM one d1, one d2, i 
        WHERE d1.sale = 'NO' AND d2.sale = 'NO'
          AND d1.datum = (d2.datum - i) 
          AND i > 0 AND i <= 3 
        GROUP BY d1.datum 
        HAVING COUNT (*) = 3) 
    AND o4.datum <= o3.datum + 3 
    AND o4.datum >= o3.datum; 
     customer | product |   datum    | sale 
    ----------+---------+------------+------
     X        | A       | 2010-02-06 | NO
     X        | A       | 2010-02-07 | NO
     X        | A       | 2010-02-08 | NO
     X        | A       | 2010-02-09 | NO
    

提交回复
热议问题