C
C
Cat Anton2016-05-28 16:18:55
MySQL
Cat Anton, 2016-05-28 16:18:55

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 |

Said, thought, googled - done: sqlfiddle.com/#!9/c9c30b/1/0 .
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`;

But now there is a need to put this query into a view (VIEW), and here two problems arise:
1. You cannot use subqueries inside FROM in views. You can work around this by creating an additional view for the subquery.
2. Variables cannot be used in views. And now this is a problem. I couldn't think of a solution to this problem without using variables. Therefore, I turn to the community, I will be grateful for any help.
I really would not want to abandon the view, since the real query is very large (with a bunch of JOIN, UNION, and so on). And you need to work with its result from the code as with one table, i.e., be able to additionally sort, filter, group, limit, etc.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artyom Karetnikov, 2016-05-28
@art_karetnikov

Procedure? :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question