Input
ID RowID Data
1 1 S
1 1 Q
1 1 L
1 1 Null
1 1 Null
1 1 S
1 1 E
1 1 R
1 1 V
1 1 E
1 1 R
1 1 Null
1 1 DB
1 2 S
1 2 T
1 2 A
1 2 C
1 2 K
2 1 O
2 1 V
2 1 E
2 1 R
2 1 Null
2 1 Null
2 1 Null
2 1 F
2 1 L
2 1 O
2 1 W
Expected Output
ID NewData
1 SQL2SERVER1DB,STACK
2 OVER3FLOW
The only way to guarantee the order of the output is to add an column which defines the correct order to the table – I’ve used an
IDENTITYcolumn.I’ve also assumed that there is a mistake in your sample data creation script (see my comment on the question) – the revised sample data creation script is as follows:
It’s not possible, as far as I can see, to correctly aggregate the
NULLrows and concatenate the strings in a single step, so this solution uses chained CTEs to carry out the steps one at a time. I’ve also used a CTE to deduplicate the output (rather than grouping).