Blockquote
I Hello Community,
I got a Problem which I wasn´t able to find a solution. It´s a problem from my work, but I changed it to explain it better.
I have some names in a table and in another I have different cities. The names are conected to the city with their ID.
Now I want to know, who lives in the city without show the city multiple times. It is like aggregating or concate the values (varchar) in one row for each city.
First I created the tables:
drop table if exists question;
CREATE TABLE question (
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
Last_Name VARCHAR(30),
First_Name VARCHAR(30),
Birthday VARCHAR(30)
);
insert into question (Last_Name,First_Name,Birthday)
values ('Mueller','Max','01.09.1989')
,('Doe','Jane','02.09.1989')
,('Musterman','Heike','01.09.1989')
,('Perez','Juliana','03.09.1989')
,('Mezu','Maria Fernanda','04.09.1989')
,('Delgado','Luis','02.09.1989')
,('McFarmer','Madleine','01.09.1989')
,('Estrella','Anna','03.09.1989')
,('Flores','Eleazar','04.09.1989');
drop table if exists cuidad;
CREATE TABLE cuidad (
cuidad_id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
city VARCHAR(30),
hab_id INT
);
insert into cuidad (hab_id,city)
values ('1','Frankfurt')
,('2','New York')
,('3','Frankfurt')
,('4','Santiago de Cali')
,('5','Pereira')
,('6','Santiago de Cali')
,('7','New York')
,('8','Pereira')
,('9','Santiago de Cali');
Now I want something like this:
Santiago de Cali | Perez - Delgado - Flores
I tried it with this code:
SELECT
c.city
,CASE WHEN
LEAD(q.Last_Name,1) OVER(PARTITION BY c.city ORDER BY id ASC) IS NOT NULL THEN
concat(q.Last_Name,' - ' ,LEAD(q.Last_Name,1) OVER(PARTITION BY c.city ORDER BY id ASC))
End as Name_aggr
FROM question q LEFT JOIN cuidad c
ON q.id=c.hab_id;
But it doesn´t work well. I got two problems
- For each row it only concate two citizens
- It repeats it with every citizien, so I got 'A - B', 'B - C', NULL
Here is the output:
It doesn´t matter if it is in one row o it is in a few row with pivoting.
Many thanks in advance.