Pardon the lack of correct terminology, I'm a professional software engineer usually dealing with Direct3D frameworks. I'm self taught on databases.
I have a _People
table and an _Ethnicities
table. Since people may have more than one cultural group I have a link table _linkPersonEthnicity
. Sample data is shown below:
What I want is output in the following form:
To illustrate the problem I present the following (runnable) query:
select lPE.Person, Sum(E.ID) as SumOfIDs,
Ethnicity = stuff(
(select ', ' + Max(E.Name) as [text()]
from _linkPersonEthnicity xPE
where xPE.Person = lPE.Person
for xml path('')
),
1, 2, '')
from _Ethnicities E
join _linkPersonEthnicity lPE on lPE.Ethnicity = E.ID
group by lPE.Person
It returns the Person's ID, a sum of the IDs found for the person's ethnicity, and concatenates the maximum Name
with commas. The data is grouped correctly, and the SumOfIDs works, proving the correct data is used.
Naturally I would like to take away the Max
aggregate function, but cannot since it is not in the group by
list.
Any ideas how to make this work?
Thanks in advance,
AM
(Many thanks to other answers on StackOverflow for getting me this far! Particiularly @Jonathan Leffler for his explanation of the partitioning proceess and @Marc_s for illustrating a text concatenation technique.)
I've also tried coalesce
from an answer to concatenating strings by @Chris Shaffer
declare @Names VARCHAR(8000)
select @Names = COALESCE(@Names + ', ', '') + E.Name
from _Ethnicities E join _linkPersonEthnicity lPE on lPE.Ethnicity = E.ID
where lPE.Person = 1001;
select @Names
Same problem. If I remove the where
and add group by
the text field Name
cannot be accessed.