计算重复的行值而不会中断

时间:2019-06-11 12:40:37

标签: mysql sql sequence repeat

我想不间断地逐行计算重复值。如果它以NULL值中断,则从零开始重新计数。

这是一个由action_id和event_code组成的简单表。

| id | action_id  | event_code |
--------------------------------
| 1  |     1      |    100     |
| 2  |     1      |    200     |
| 3  |     1      |    300     |
| 4  |     2      |    100     |
| 5  |     2      |    300     |
| 6  |     3      |    100     |
| 7  |     3      |    200     |
| 8  |     3      |    400     |

然后按action_id(使用SQL查询)将其分组为:

| action_id | c100 | c200 | c300 | c400 |
-----------------------------------------
|     1     |  1   |  1   |  1   |  0   |
|     2     |  1   |  0   |  1   |  0   |
|     3     |  1   |  1   |  0   |  1   |

结果:

| action_id | c100 | e100_r | c200 | e200_r | c300 | e300_r | c400 | e400_r |
-----------------------------------------------------------------------------
|     1     |  1   |   3    |  1   |   1    |  1   |   2    |  0   |   0    |
|     2     |  1   |   3    |  0   |   0    |  1   |   2    |  0   |   0    |
|     3     |  1   |   3    |  1   |   1    |  0   |   0    |  1   |   1    |

| id | action_id  | event_code | rep_count |
--------------------------------------------
| 1  |     1      |    100     |     3     |
| 2  |     1      |    200     |     1     |
| 3  |     1      |    300     |     2     |
| 4  |     2      |    100     |     3     |
| 5  |     2      |    300     |     2     |
| 6  |     3      |    100     |     3     |
| 7  |     3      |    200     |     1     |
| 8  |     3      |    400     |     1     |

有可能吗?

编辑1: c100-event_code == 100和e100_r-重复event_code == 100

编辑2: 行中断为零(0)

0 个答案:

没有答案