I have a column in a table that is json. It contains several columns within it.
Example:
- Row1:
"sTCounts":[{"dpsTypeTest":"TESTTRIAL","cnt":3033244.0} - Row2:
"sTCounts":[{"dpsTypeTest":"TESTTRIAL","cnt":3.3}
I need to sum the cnt value for all rows in table. For instance, the above would produce a result of 3033247.3
I'm not familiar with stored procs enough to master. I thought the easiest route would be to create a temp table and extract the value into a column, and then write a query to sum the column values.
The problem is that it creates a column with datatype nvarchar(4000). It won't let me sum that column. I thought of changing the datatype but not sure how. I am trying CAST without luck.
select CAST(json AS varchar) AS JSON_VALUE(jsontext,
'$.sTCounts.cnt') AS PerfCount, TitleNumber
INTO dbo_Testing_Count0
from PerformanceTest
select sum(PerfCount)
from dbo_Testing_Count
Group by PerfCount
The error message is:
Incorrect syntax near 'jsontext'.
Any ideas? I am open to another method to sum the column or changing the datatype whichever the experts can aid on. I appreciate it.
JSONTEXT, not yourSUM. You haveCAST(json AS varchar) AS JSON_VALUE(jsontext, '$.serviceTierCounts.cnt') AS PerformanceCount,which makes little sense. It looks like you forgot the alias after the firstAS. Also, never declare avarcharand not declare it's length.'$.serviceTierCounts.cnt'returns a integer value, eitherCAST/CONVERTit in theSELECTor useOPENJSONwith aWITHto define the structure of your JSON data.