简体   繁体   English

MySQL-如何计算当前行中先前出现的次数

[英]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. 例如,在第1天,平台1670254执行了3次先前的操作。

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 SQL演示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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