2

Is there any way to change a SQL query that would normally return multiple rows with the same values into a single row?

for example, if my existing query returns this:

ColA ColB
1    AA
1    BB
1    CC
2    AA
3    AA

could I change the query to have only 3 rows returned and to place the 2nd and 3rd result for 1 into the first row, so that you'd have a row of: 1 AA BB CC?

5
  • Look into DISTINCT or the GROUP BY statement. Commented Jul 30, 2013 at 22:37
  • Also look into union. Commented Jul 30, 2013 at 22:38
  • What database are you using? Commented Jul 30, 2013 at 22:38
  • @kmfmd: I reverted to my edit with the inline table. I think it explains everything perfectly and then you don't need to worry about image hosts being blocked. Commented Jul 30, 2013 at 22:39
  • possible duplicate of Combine multiple results in a subquery into a single comma-separated value Commented Jul 31, 2013 at 12:17

1 Answer 1

1

Not really nice but working(I'm missing group_concat from MySql):

SELECT ColA, 
       ColB=STUFF(
             (SELECT ' ' + ColB 
              FROM dbo.Table1 t2
              WHERE t1.ColA = t2.ColA 
              FOR XML PATH (''))
             , 1, 1, '')
FROM dbo.Table1 t1
GROUP BY ColA

Demo

[ Edit: for any reason presumed SQL-Server ]

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I am using MS SQL Server. I will give this a try tomorrow, thanks. Does that limit to 3 occurrences, though? Is there a way to generate it in the desired format regardless of how many occurrences you might have?
@kmfdm: the size if the groups doesn't matter.
I suggest to use value function, like this - stuff((select ' ' + ColB from dbo.Table1 as t2 where t2.ColA = t1.ColA for xml path('')).value('.', 'nvarchar(max)'), 1, 1, ''), otherwise your solution is not correct for arbitrary strings, like 'A&A', for example. Also see this answer stackoverflow.com/a/12940952/1744834 for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.