Answer the question
In order to leave comments, you need to log in
How to create a view with a grouping of adjacent rows?
All the best.
There was a need to group adjacent rows with the same values of certain fields.
For simplicity, from such a table (on the left) you need to get this (on the right):
| id | num | | num | count |
|----|-----| |-----|-------|
| 1 | 1 | | 1 | 2 |
| 2 | 1 | | 2 | 1 |
| 3 | 2 | | 1 | 3 |
| 4 | 1 | | 3 | 2 |
| 5 | 1 | | 4 | 1 |
| 6 | 1 |
| 7 | 3 |
| 8 | 3 |
| 9 | 4 |
SELECT `num`, COUNT(`group`) AS `count`
FROM(
SELECT
`id`, `num`,
IF (@prev = `num`, @group, @group := @group + 1) AS `group`,
@prev := `num` AS `prev`
FROM `test`
JOIN (SELECT @prev := 0, @group := 0) AS `t1`
) AS `t2`
GROUP BY `group`;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question