I have 2 tables as following
---------------------------------
| PId | uniid |
|-----|------------------------ |
| 1 | xxxggsgsg |
| 3 | xxxxxggsgs |
| 4 | xxxxxggsgsg |
| 5 | gfgjsfgjf |
| 6 | gsgjsfgjf |
| 7 | gfgjsfgjf |
----------------------------------
---------------------------------------
| PId | email |
|-----|-------------------------------|
| 4 | [email protected] |
| 6 | [email protected] |
| 7 | [email protected] |
| 9 | [email protected] |
| 1 | [email protected] |
| 22 | [email protected] |
| 1 | [email protected] |
---------------------------------------
And I want to display the uniid of the matched ids in both the tables and my query was
select email,count(email) as EmailCount , (STUFF((SELECT CAST(', ' + t1.uniid AS VARCHAR(MAX))
FROM t1
join t2
on t1.PId = t2.PId
group by t1.uniid
FOR XML PATH ('')), 1, 2, '')) AS uni
from t1
inner join t2
on t1.PId = t2.PId
group by email
And my output is
+------------------------------------------------------------------------------------------------------+
| email | EmailCount | uniid |
--------------------------------------------------------------------------------------------------------
| [email protected] | 1 | gfgjsfgjf , gsgjsfgjf , xxxxxggsgsg |
--------------------------------------------------------------------------------------------------------
|[email protected] | 1 | gfgjsfgjf , gsgjsfgjf , xxxxxggsgsg |
-------------------------------------------------------------------------------------------------------
|[email protected] |3 | gfgjsfgjf , gsgjsfgjf , xxxxxggsgsg |
+-----------------------------------------------------------------------------------------------------+
Here the column is showing 3 even when the 3 uniids when the count is even. How can I show only the uniid for the matched pid. My sql fiddle is Sample DB