I have a problem creating a SQL-statement for sqlserver2008. I have the following data:
city person priority
-----------------------------------
Linz Mike 1
Wien Mike 1
Linz Tom 1
Wien Tom 1
Linz John 1
Linz Sarah 2
This means that the persons Mike and Tom choose the cities Linz and Wien with priority 1.
John chooses Linz with priority 1.
Sarah chooses Linz with priority 2.
now I want the following output:
cities persons priority
-----------------------------------
Linz, Wien Mike, Tom 1
Linz John 1
Linz Sarah 2
I already have following SQL-Statement but I do not get the expected result as this query would say that John also has an entry for Wien with priority 1.
SELECT
(SELECT
STUFF((SELECT ', ' + d.City
FROM (SELECT DISTINCT d2.City FROM dbo.DummyTable d2
WHERE d2.Priority = d1.Priority) d
FOR XML PATH('')), 1, 2, '')
)
AS Cities,
(SELECT
STUFF((SELECT ', ' + d.Person
FROM (SELECT DISTINCT d2.Person FROM dbo.DummyTable d2
WHERE d2.Priority = d1.Priority) d
FOR XML PATH('')), 1, 2, '')
)
AS Persons,
d1.Priority
FROM
dbo.DummyTable d1
GROUP BY d1.Priority
You can also use this SQL Fiddle
Any ideas how this query could be written in SQL?