简体   繁体   中英

MySQL - How to count number of previous occurrences to current row

With the following table:

+----------+------+
| Platform | day  |
+----------+------+
| 1670254  |    0 |
| 1670254  |    0 |
| 1665087  |    0 |
| 1670254  |    0 |
| 1670254  |    1 |
| 1670254  |    1 |
| 1670254  |    1 |
| 1670254  |    1 |
| 1670254  |    1 |
| 1665160  |    1 |
| 1670254  |    1 |
| 1670254  |    2 |
| 1670254  |    2 |
| 1670254  |    3 |
| 1670254  |    4 |
| 1667145  |    5 |

I want to add a third column that counts the number of occurrences of previous dates. For example, on day 1, platform 1670254 performed 3 previous operations.

The result should show something like:

+----------+------+-----------+
| Platform | day  |  Previous | 
+----------+------+-----------+
| 1670254  |    0 |     0     |
| 1670254  |    0 |     0     |
| 1665087  |    0 |     0     |
| 1670254  |    0 |     0     |
| 1670254  |    1 |     3     |
| 1670254  |    1 |     3     |
| 1670254  |    1 |     3     |
| 1670254  |    1 |     3     |
| 1670254  |    1 |     3     |
| 1665160  |    1 |     0     |
| 1670254  |    1 |     3     |
| 1670254  |    2 |     9     |
| 1670254  |    2 |     9     |
| 1670254  |    3 |    11     |
| 1670254  |    4 |    12     |
| 1667145  |    5 |     0     |

Just need a correlated query to get the previous day for each platform.

SQL DEMO

   SELECT *, (SELECT COUNT(Platform) 
              FROM YourTable t2 
              WHERE t1.Platform = t2.Platform
                AND t1.day > t2.day) as Previous
   FROM YourTable t1

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