I have the following table:
Code Ref Value
A1 Car A
A1 Car -
A1 Car B
B2 Truck CC
B2 Truck D
B2 Truck -
C3 Van E
C3 Van F
C3 Van -
C3 Van G
The goal I am trying to accomplish, is a concatenated string grouping all of the values together like this:
Code Ref Value
A1 Car A-B
B2 Truck CCD-
C3 Van EF-G
I went off of the example here, but got nowhere. Here is what I came up with:
SELECT [Table].[Code]
, [Table].[Ref]
, STUFF((SELECT DISTINCT [Value]
FROM [Table2]
FOR XML PATH ('')),1, 1,'') AS Values
FROM [Table]
LEFT JOIN [Table2] ON
[Table2].[Code] = [Table].[Code]
Where am I going wrong? Is there a more efficient way to do this?
You have nothing linking your inner and outer references to
[Table], and you also need to make the outer reference distinct. Finally you need to either have no column name within your subquery, or it needs to be[text()]As an aside, you do not need to use
STUFFas you have no delimiter,STUFFis typically used to remove the chosen delimiter from the start of the string. So when you have a string like,value1,value2,value3,STUFF(string, 1, 1, '')will replace the first character with''leaving you withvalue1,value2,value3.You should also use the
valuexquery method to ensure you are not tripped up by special characters, if you don't and you try an concatenate">>"and"<<"you would not end up with">><<"as you might want, you would get">><<", so a better query would be:ADDENDUM
Based on the latest edit to the question it appears as though your
Valuecolumn is coming from another table, linked to the first table byCode. If anything this makes your query simpler. You don't need theJOIN, but you still need to make sure that there is an expression to link the outer table to the inner table your subquery. I am assuming that the rows are unique in the first table, so you probably don't need the group by either:WORKING EXAMPLE