Skip to content
Advertisement

SQL – Calculate number of occurrences of previous day?

I want to calculate the number of people who also had occurrence the previous day on a daily basis, but I’m not sure how to do this?

Sample Table:

| ID |   Date    |
+----+-----------+
|  1 | 1/10/2020 |
|  1 | 1/11/2020 |
|  2 | 2/20/2020 |
|  3 | 2/20/2020 |
|  3 | 2/21/2020 |
|  4 | 2/23/2020 |
|  4 | 2/24/2020 |
|  5 | 2/22/2020 |
|  5 | 2/23/2020 |
|  5 | 2/24/2020 |
+----+-----------+

Desired Output:

|   Date    | Count |
+-----------+-------+
| 1/11/2020 |     1 |
| 2/21/2020 |     1 |
| 2/23/2020 |     1 |
| 2/24/2020 |     2 |
+-----------+-------+

Edit: Added desired output. The output count should be unique to the ID, not the number of date occurrences. i.e. an ID 5 can appear on this list 10 times for dates 2/23/2020 and 2/24/2020, but that would count as “1”.

Advertisement

Answer

Use lag():

select date, count(*)
from (select t.*, lag(date) over (partition by id order by date) as prev_date
      from t
     ) t
where prev_date = dateadd(day, -1, date)
group by date;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement