sql server - SQL-statement for two group-columns -
i have problem creating sql-statement sqlserver2008. have 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 persons mike , tom choose cities linz , wien priority 1.
john chooses linz priority 1.
sarah chooses linz priority 2.
now want following output:
cities persons priority ----------------------------------- linz, wien mike, tom 1 linz john 1 linz sarah 2
i have following sql-statement not expected result query john has entry wien priority 1.
select (select stuff((select ', ' + d.city (select distinct d2.city dbo.dummytable d2 d2.priority = d1.priority) d xml path('')), 1, 2, '') ) cities, (select stuff((select ', ' + d.person (select distinct d2.person dbo.dummytable d2 d2.priority = d1.priority) d xml path('')), 1, 2, '') ) persons, d1.priority dbo.dummytable d1 group d1.priority
you can use sql fiddle
any ideas how query written in sql?
here's way it:
;with personcitygrouppreferences ( select person, priority, stuff (( select ', ' + d2.city dummytable d2 d1.priority = d2.priority , d1.person = d2.person xml path('') ), 1, 2, '') cities dummytable d1 group person, priority ) select cities, stuff (( select ', ' + p2.person personcitygrouppreferences p2 p1.cities = p2.cities , p1.priority = p2.priority xml path('') ), 1, 2, '') persons, priority personcitygrouppreferences p1 group priority, cities
sqlfiddle link: http://www.sqlfiddle.com/#!3/d831d/57
in order achieve final result, divided solution 2 steps:
obtain result set groups data
person
,priority
, contains comma-separated list of cities third columntake result set obtained point 1 , same thing, group columns
cities
(the comma-separated list) ,priority
, produce comma-separated list of corresponding persons.
in query above, step 1 query:
select person, priority, stuff (( select ', ' + d2.city dummytable d2 d1.priority = d2.priority , d1.person = d2.person xml path('') ), 1, 2, '') cities dummytable d1 group person, priority
here's how partial results in sql: http://www.sqlfiddle.com/#!3/d831d/58
i exposed first query cte, making available (outer) query 2, same thing, different grouping criteria.
Comments
Post a Comment