I need to display a table column (assume 2 columns) values with comma-separated in the output
Table t1:
col1 Col2
================
xyz ab/cde
pqr uv/wxy
xyz fg/hij
lmn rtg
pqr 12/456
Table t2:
col1
======
xyz
pqr
Output needed:(column col2 to be populated in table2 with following values)
col1 Col2
================
xyz ab,fg
pqr uv,12
Output expected :
- col1 values of t1 should be equal to col1 values of t2.
- For the records passing step1, take col2 values before slash from t1 and have them comma separated for each value of col1.
- EDITED :
How to get only distinct values from col2 of t1 table. Ex: if the values of the table are
col1 Col2
================
xyz ab/cde
pqr uv/wxy
xyz fg/hij
lmn fg
pqr fg/456 tehn output to be only ab,fg,uv...
Can anyone please help me on this?I'm not getting on how to do it in sql server.
Assuming a version that supports
STRING_AGG:If you want the resulting string to contain values from
t2.col2that don't contain slashes (ambiguous given the sample data), change theNULLIFline to:And yes, if you want to code golf me, you could change...
...to...
Edited Answer:
To prevent duplicates, you have to use
DISTINCTorGROUP BYon the substring. I avoid duplicating theLEFT/SUBSTRINGlogic by using a CTE. There are certainly other ways (likeCROSS APPLYperhaps).