Answer the question
In order to leave comments, you need to log in
How to find longest prefix among strings and group by it?
Hello! Already spammed the whole Google, but what he gave out, he could not apply.
I could only find that a similar task is called Longest common prefix(LCP)
There is an example table:
+----+-----------+------------------------+
| id | parent_id | path |
+----+-----------+------------------------+
| 1 | 7 | val10/val11/val12/val3 |
| 2 | 7 | val1/val2/val3/val5 |
| 3 | 7 | val1/val2/val3/val6 |
| 4 | 7 | val1/val2/val3/val7 |
| 5 | 7 | val1/val2/val3/val8 |
| 6 | 7 | val1/val2/val3/val9 |
+----+-----------+------------------------+
+-----------+------------------------+-------+
| parent_id | path | count |
+-----------+------------------------+-------+
| 7 | val1/val2/val3 | 5 |
| 7 | val10/val11/val12/val3 | 1 |
+-----------+------------------------+-------+
create table example (id int, parent_id int, path varchar(50));
insert into example
select 1, 7, 'val10/val11/val12/val3'
union select 2, 7, 'val1/val2/val3/val5'
union select 3, 7, 'val1/val2/val3/val6'
union select 4, 7, 'val1/val2/val3/val7'
union select 5, 7, 'val1/val2/val3/val8'
union select 6, 7, 'val1/val2/val3/val9'
Answer the question
In order to leave comments, you need to log in
um,,, select path, count(*) from example group by path ?
Or am I not quite understanding something?
As for me - the task is set incorrectly. Or there are not enough additional conditions. For example, I think that the general prefix should be like this.
+-----------+------------------------+-------+
| parent_id | path | count |
+-----------+------------------------+-------+
| 7 | val1 | 6 |
+-----------+------------------------+-------+
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question