SQL group by a combined value from two columns

Viewed 34

I have the following table

table

and I need this query result

result

I basically have to make a "unique" value from the columns Nr and S. Then I need to group by this new unique value.

How do I do this.

1 Answers

starting from SQL Server 2017 you could use string_agg

select id, concat(nr,'-',s) nr_s, k, s
  , STRING_AGG(z_value, ';') z_value
  , STRING_AGG(x_value, ';') x_value
  , STRING_AGG(y_value, ';') y_value
from my_table  
group by id, concat(nr,'-',s), k, s
Related