How to find N Consecutive records in a table using SQL

前端 未结 4 976
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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 12:57

    You need to match your table against itself, as if there where 2 tables. So you use two aliases, o1 and o2 to refer to your table:

    SELECT DISTINCT o1.customer, o1.product, o1.datum, o1.sale
      FROM one o1, one o2
      WHERE (o1.datum = o2.datum-1 OR o1.datum = o2.datum +1)
      AND o1.sale = 'NO' 
      AND o2.sale = 'NO'; 
     customer | product |   datum    | sale 
    ----------+---------+------------+------
     X        | A       | 2010-01-03 | NO
     X        | A       | 2010-01-04 | NO
     X        | A       | 2010-01-06 | NO
     X        | A       | 2010-01-07 | NO
     X        | A       | 2010-01-08 | NO
    

    Note that I performed the query on an postgresql database - maybe the syntax differs on ms-sql-server, maybe at the alias 'FROM one AS o1' perhaps, and maybe you cannot add/substract in that way.

提交回复
热议问题