1

A Table can have multiple records for each key as below.

Actual Table:

Key         Value
----------- ---------
2149        805501   
2149        800936   
15385       800622   
18105       997057   
18105       999390   

Expected result:

Key         Value
----------- ---------
2149         805501,800936
15385       800622   
18105       997057,999390   

I'm unable to think of a solution here. Any help is much appreciated.

Hadi
  • 36,233
  • 13
  • 65
  • 124
BetterLateThanNever
  • 886
  • 1
  • 9
  • 31
  • You can use a sub select for your value column using FOR XML to comma separate the values. Should your key be 2149 not 219 in the expected result? – David B Dec 12 '17 at 22:33
  • Why do you want to do this? It's a SQL anti-pattern. The generally best answer would be "don't". – MatBailie Dec 12 '17 at 22:36
  • 1
    Possible duplicate of [Concatenate many rows into a single text string?](https://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string) – Caius Jard Dec 12 '17 at 23:23

2 Answers2

3

You should use FOR XML PATH:

Select Key, STUFF((SELECT ',' + VALUE
                   FROM Table AS T2 
                   WHERE T1.Key = T2.Key
                  FOR XML PATH('')), 1, 1, '') 
FROM Table T1
GROUP BY Key

UPDATE 1

based on your comments

enter image description here

Hadi
  • 36,233
  • 13
  • 65
  • 124
-1

I think the answer is the actual table in the top of your question, You cant relate values of a key in that way in database tables

developer_009
  • 317
  • 3
  • 11
  • This is not correct as you can select out data and display it differently to how it is stored. Also the table shown above does not have a primary key defined and key is not unique. – David B Dec 12 '17 at 22:38
  • Why can't you create a table with both columns as primary keys, so when you need records with the key 2149 for example you get all the values that associate with that key ? – developer_009 Dec 12 '17 at 22:41
  • 1
    Like the following? Key 2149 Value 805501,805502. This should be done in the presentation of data not in the way its stored. Storing like this would prove difficult in the future to retrieve values. – David B Dec 12 '17 at 22:49