943,712 Members | Top Members by Rank

Ad:
  • MS SQL Discussion Thread
  • Unsolved
  • Views: 6798
  • MS SQL RSS
Jul 2nd, 2009
0

How to combine multiple rows's column into one column

Expand Post »
Hello, i have face problem when i need to retrieve data from database (SQL 2000). Below my table :

Column A | Column B
1 a
1 b
2 c
2 d

i need the result is :

Column A | Column B
1 a b
2 c d

Can anyone tell me how to write the sql command?
Similar Threads
Reputation Points: 10
Solved Threads: 0
Light Poster
nokomoli is offline Offline
26 posts
since Nov 2007
Jul 2nd, 2009
0

Re: How to combine multiple rows's column into one column

sql Syntax (Toggle Plain Text)
  1. /*
  2. Column A | Column B
  3. 1 a
  4. 1 b
  5. 2 c
  6. 2 d
  7. */
  8.  
  9. IF OBJECT_ID('Table1', 'U') IS NOT NULL DROP TABLE Table1
  10. CREATE TABLE Table1
  11. (
  12. ColumnA INT,
  13. ColumnB VARCHAR(1)
  14. )
  15.  
  16. GO
  17.  
  18. INSERT INTO Table1 (ColumnA, ColumnB) VALUES (1, 'a')
  19. INSERT INTO Table1 (ColumnA, ColumnB) VALUES (1, 'b')
  20. INSERT INTO Table1 (ColumnA, ColumnB) VALUES (2, 'c')
  21. INSERT INTO Table1 (ColumnA, ColumnB) VALUES (2, 'd')
  22.  
  23. GO
  24.  
  25. GO
  26.  
  27. IF OBJECT_ID('dbo.JoinString', 'FN') IS NOT NULL DROP FUNCTION dbo.JoinString
  28.  
  29. GO
  30.  
  31. CREATE FUNCTION dbo.JoinString (@ColumnA INT)
  32. RETURNS VARCHAR(100)
  33. AS
  34. BEGIN
  35.  
  36. DECLARE @result VARCHAR(100)
  37. SET @result = ''
  38. SELECT @result = @result + ' ' + IsNull(ColumnB, '')
  39. FROM Table1
  40. WHERE ColumnA = @ColumnA
  41. ORDER BY ColumnB
  42.  
  43. return LTRIM(@result)
  44. END
  45.  
  46. GO
  47.  
  48. DECLARE @Tab Table
  49. (
  50. ColumnA INT,
  51. ColumnB VARCHAR(100)
  52. )
  53.  
  54. INSERT INTO @Tab (ColumnA) SELECT DISTINCT(ColumnA) FROM Table1 (NOLOCK)
  55. UPDATE @Tab SET ColumnB = dbo.JoinString(ColumnA)
  56.  
  57.  
  58. SELECT *
  59. FROM @Tab
Featured Poster
Reputation Points: 1749
Solved Threads: 735
Senior Poster
sknake is offline Offline
3,948 posts
since Feb 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in MS SQL Forum Timeline: Code inside CATCH not execute
Next Thread in MS SQL Forum Timeline: joining the table





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC