Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pulling floats to sum data in array structure using SQL

I’m trying to pull numbers from an array structure and then I want to sum them.

Example row entry:

{"DBA":50.0},{"RST":132.0},{"ZIT":752}

I would want to sum all of the number values so 50 + 132 + 752 = 934

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What I have tried: col = column name

SELECT SUBSTRING(col, LEN(LEFT(col, CHARINDEX (':', col))) + 1, LEN(col) - LEN(LEFT(col, 
    CHARINDEX (':', col))) - LEN(RIGHT(col, LEN(col) - CHARINDEX ('}', Benefit))) - 1)    
FROM table

This works to grab the first value (so 50.0) in the above example, but will not grab each value. Any idea how I can make this query grab multiple values and then sum them together?

>Solution :

The content is almost a valid JSON, so you may try to fix it and parse it with built-in JSON support using OPENJSON() (a valid JSON content is [{"DBA":50.0},{"RST":132.0},{"ZIT":752}]):

SELECT 
  t.[Column],
  [Sum] = (
     SELECT SUM(CONVERT(numeric(10, 1), j2.value)) 
     FROM OPENJSON(CONCAT('[', t.[Column], ']')) j1
     CROSS APPLY OPENJSON(j1.[value]) j2
  )
FROM (VALUES
   ('{"DBA":50.0},{"RST":132.0},{"ZIT":752}')
) t ([Column])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading