UDVを使用した累積合計:
select
dateOfCheckup,
duration,
-- use intermediate variable @cur_dur for not calculate this value twice
@cur_dur := ((case when duration like '% hour%' then substring_index(duration, ' hour', 1) * 60 else 0 end) +
(case when duration like '%min%' then substring_index(substring_index(duration, ' min', 1), ' ', -1) + 0 else 0 end)) as minutes,
-- check does current @year_month is equal to previous, continue or restart @cum_sum
CASE WHEN @year_month = date_format(dateOfCheckup, '%Y-%m')
THEN @cum_sum := @cum_sum + @cur_dur
ELSE @cum_sum := @cur_dur
END total,
-- store current @year_month for to use with next row
@year_month := date_format(dateOfCheckup, '%Y-%m') monthOfCheckup
from patient,
-- initialize variables which will be used
(SELECT @year_month:='', @cum_sum:=0, @cur_dur:=0) variables
-- the rows must be processed in definite order
ORDER BY dateOfCheckup
出力列の順序は重要です(行の出力列の計算は、書き込まれた順序で厳密に実行されます)。ただし、この例をサブクエリとして使用するか、出力データに列名でアクセスするかは関係ありません。