I have rows in a table like this:
ORG | Tenant | Dimension | Count |
---|---|---|---|
A | T1 | MAU | 100 |
A | T1 | WAU | 70 |
B | T2 | MAU | 50 |
B | T2 | Retention | 30 |
Now I need to group based on ORG, Tenant and remaining columns I need to convert into a single JSON as below.
ORG | Tenant | CustomData |
---|---|---|
A | T1 | {MAU:100,WAU:70} |
B | T2 | {MAU:50,Retention:30} |
How can I achieve this in SQL Server or using C#? Do we have an out of the box support for this?
Thanks for your help,
Nikesh
3
Answers
Any specific solution is relative to your environment and it may not perform fast enough. However, You can use C# to reshape your list of records. Create a new JSON Object like so:
Achieve with LINQ-to-SQL expression.
First group by
Org
andTenant
, for the grouping result part, theCustomData
property is applied as Dictionary/KeyValuePair.Sample .NET Fiddle
Note:
As the
CustomData
is applied as Dictionary/KeyValuePair, the key must be unique before mapping. If in the input data there are the records with the sameOrg
,Tenant
, andDimension
, then you need to group these 3 properties/columns and perform an aggregate sum first.your data
For Json Path
changeSql
tables intoJson
data, but you can get your desired result by usingString_agg
andConcat
dbfiddle