JSON - multiple aggregations extremely slow

G P 41 Reputation points
2021-02-12T13:28:51.163+00:00

Select col1
,sum(json_value(json_field,’$.col2’))
,sum(json_value(json_field,’$.col3’))
,sum(json_value(json_field,’$.col4’))
,sum(json_value(json_field,’$.col5’))
,avg(json_value(json_field,’$.col6’))
,max(json_value(json_field,’$.col7’))
From table1
Group by col1

The table has 78000 rows. Json_field has a json structure with 600 attributes. When I perform just one aggregation it takes less than 1 sec. The performance degrades with addition of each aggregation. The query takes 17 seconds which is not acceptable. When I perform each aggregation on its own the six queries finish in 6 sec. This tells me there is repeated parsing happening with each additional json_value.

I am new to json in sql server. Any help here would be of great value.

Thanks!

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,060 questions
{count} votes

Accepted answer
  1. Viorel 113.7K Reputation points
    2021-02-12T14:46:20.537+00:00

    Try two other possibilities:

    select col1,
       sum(json_value(j, '$.col2')),
       sum(json_value(j, '$.col3')),
       . . .
    from Table1
    cross apply (values (json_query(json_field, '$'))) t(j)
    group by col1
    

    and

    select col1,
       sum(col2),
       sum(col3),
       . . .
    from Table1
    cross apply openjson(json_field) with 
        ( 
            col2 int '$.col2', 
            col3 int '$.col3',
            . . .
        )
    group by col1
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful