MySQL Labs JSON native type: How SUM the result of an array returned by jsn_extract? MySQL Labs JSON native type: How SUM the result of an array returned by jsn_extract? json json

MySQL Labs JSON native type: How SUM the result of an array returned by jsn_extract?


I tried to use @Rick's answer but it didn't work for me. So I digged mysql documentation for mysql functions. Here's the working function for mysql 5.7.14,

create function sum_array_cells( input_array json )returns doubleBEGIN    DECLARE array_length INTEGER(11);    DECLARE retval DOUBLE(19,2);    DECLARE cell_value DOUBLE(19,2);    DECLARE idx INT(11);    SELECT json_length( input_array ) INTO array_length;    SET retval = 0.0;    SET idx = 0;    WHILE idx < array_length DO        SELECT json_extract( input_array, concat( '$[', idx, ']' ) )            INTO cell_value;        SET retval = retval + cell_value;        SET idx = idx + 1;    END WHILE;    RETURN retval;END

Then use the function as @Rick wrote:

select sum_array_cells( '[ 0.89, 12.99, 5.23, 2.04 ]' );


Use JSON_TABLE see example:

SET @datax = '[  { "product":"apple",  "price": 5},   { "product":"banana",  "price": 7}]';SELECT price.* FROM      JSON_TABLE(@datax, '$[*]' COLUMNS (                price INTEGER PATH '$.price')     ) price;`

Then, add up the price.


The following stored function does the trick for me:

delimiter $$create function sum_array_cells( input_array json )returns doublelanguage sql deterministic contains sqlbegin    declare array_length integer;    declare retval double;    declare cell_value double;    declare idx int;    select json_length( input_array ) into array_length;    set retval = 0.0;    set idx = 0;    while idx < array_length do        select json_extract( input_array, concat( '$[', idx, ']' ) )        into cell_value;        set retval = retval + cell_value;        set idx = idx + 1;    end while;    return retval;end$$

Then you would invoke that function in a query like this

select sum_array_cells( '[ 0.89, 12.99, 5.23, 2.04 ]' );

Hope this helps,-Rick