Click here to Skip to main content
15,891,703 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SELECT one column (val3), with multiple columns returned where other columns (id, val1) are same, mysql query

data looks something like that

id val1 val2 val3
R  m    1    a   
N  c    1    c
N  c    2    d
Y  b    1    e
Y  h    1    u
Y  h    2    i


the result should be
id val1 val3s
R  m    a   
N  c    c,d
Y  b    e
Y  h    u,i


What I have tried:

Have done,
SELECT id, val1,  
CASE
 WHEN COUNT(val1) = 1 THEN  CONCAT('(', val3, ')')
 WHEN COUNT(val1) > 1 THEN  CONCAT('(',  '??' , ')')
END AS val3s
FROM table1
GROUP BY val1
Posted
Updated 6-Sep-16 2:44am
v4

Please try this. Hope this will help, here your table1 is TestConC

select  a.id, a.val1, CustomData
= STUFF( (SELECT ',' + b.val3 
                             FROM TestConC b    
                             where b.id=a.id and b.val1=a.val1                     
                             FOR XML PATH('')),1, 1, '')
From TestConC a
group by  a.id, a.val1
order by a.id
 
Share this answer
 
Comments
Rajesh waran 6-Sep-16 7:19am    
5+
manu_dhobale 6-Sep-16 7:21am    
Thanks
Maciej Los 6-Sep-16 7:48am    
Seems that OP wants to display only non-numeric data. Your solution is not adequate.
Richard Deeming 6-Sep-16 8:38am    
That's the solution for Microsoft SQL Server. The question is tagged as MySQL.
Sounds like you're looking for the GROUP_CONCAT function[^]:
SQL
SELECT
    id,
    val1,
    GROUP_CONCAT(val3) As val3s
FROM
    table1
GROUP BY
    id,
    val1
;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900