My result contains data like:
CustomerId | Rating (Star) | RatingCount
1 | 1 | 20
1 | 2 | 15
1 | 3 | 4
1 | 4 | 30
1 | 5 | 36
2 | 1 | 5
2 | 2 | 4
2 | 5 | 10
But I would like to transform the result as:
CustomerId | CustomerRatings
1 | { "1": 20, "2": 15, "3": 4 , "4": 30, "5": 36 }
2 | { "1": 5, "2": 4, "5": 10 }
I have used the FOR JSON Path function to transfrom the data as
@JSONString = {"_":"1","__":20},{"_":"2","__":15},{"_":"3","__":4},{"_":"4","__":30},{"_":"5","__":36}
Then used the replace method to get the actual result.
SELECT REPLACE(REPLACE(REPLACE(@JSONString,'"_":',''),',"__":',':'),'},{',',')
{"1":20,"2":15,"3":4,"4":30,"5":36}
Is there a better way to achieve that? I started using SQL server 2016 last couple of days.