简体   繁体   中英

Find rows with consecutive dates

Is it possible to know which customer came at the bar 3 consecutive days? (john in my case)

Thanks in advance

Name Age Date Amount
Paul 12 2021-12-01 20
John 19 2021-12-01 10
Jack 17 2021-13-01 7
John 19 2021-13-01 8
John 19 2021-14-01 17

so I would approach this by

SELECT FROM Table
    LEFT JOIN Table As PrevDay on PrevDay.Customer = Table.Customer 
        AND PrevDay.date = DATEADD(DAY,-1,Table.Date)
    LEFT JOIN Table AS NextDay on NextDay,Customer = Table.Customer 
        AND NextDay.Date = DATEADD(DATE,1,Table.Date)
WHERE PrevDay.Customer is not NULL 
AND NextDay.Customer is not null

Assuming that the data type of the column Date is DATE you can use a self join and aggregation:

SELECT DISTINCT t1.Name
FROM tablename t1 INNER JOIN tablename t2
ON t2.Name = t1.Name AND ABS(DATEDIFF(t1.Date, t2.Date)) = 1
GROUP BY t1.Name, t1.Date
HAVING COUNT(DISTINCT t2.Date) = 2;

Or, a more scalable solution:

SELECT DISTINCT t1.Name
FROM tablename t1 INNER JOIN tablename t2
ON t2.Name = t1.Name AND t2.Date BETWEEN t1.Date AND t1.Date + INTERVAL 2 DAY
GROUP BY t1.Name, t1.Date
HAVING COUNT(DISTINCT t2.Date) = 3;

You can remove DISTINCT from COUNT(DISTINCT t2.Date) if the combination of Name and Date is unique in the table.

See the demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM