Home >Database >Mysql Tutorial >How to Calculate a Conditional SUM in Oracle with a Reset Threshold?
Oracle provides robust functionality for conditional aggregation, including conditional SUM calculations. This article tackles the challenge of performing such a SUM, with a specific requirement: reset the accumulated value when it exceeds 15.
Problem Statement
The objective is to calculate a conditional SUM over a series of values, where the SUM is reset to zero whenever it reaches or exceeds 15. This aggregation results in a sequence of SUMs partitioned by the threshold value.
Solution: Utilizing the MODEL Clause
While recursive SQL is a viable approach, the SQL MODEL clause offers an alternative that enhances readability and streamlines the execution process.
<code class="sql">-- Create a table to represent the sample data CREATE TABLE test_data ( sort_col VARCHAR2(1), addend NUMBER ); -- Insert sample data INSERT INTO test_data (sort_col, addend) VALUES ('A', 3), ('B', 7), ('C', 6), ('D', 5), ('E', 9), ('F', 3), ('G', 8); -- Begin the actual solution WITH sorted_inputs AS ( SELECT sort_col, ROW_NUMBER() OVER (ORDER BY sort_col) AS sort_order, addend, 0 AS running_sum_max_15 -- Initialize running sum to zero FROM test_data ) SELECT sort_col, addend, running_sum_max_15 FROM sorted_inputs MODEL DIMENSION BY (sort_order) MEASURES (sort_col, addend, running_sum_max_15) RULES UPDATE ( running_sum_max_15[1] = addend[1], -- Set initial running sum to the first addend running_sum_max_15[sort_order > 1] = -- Calculate running sum for subsequent rows CASE WHEN running_sum_max_15[CV(sort_order) - 1] < 15 THEN running_sum_max_15[CV(sort_order) - 1] -- Continue running sum if below threshold ELSE 0 -- Reset running sum if threshold is reached or exceeded END + addend[CV(sort_order)] -- Add current addend to running sum );</code>
Results
The query produces the following output:
<code class="sql">+----------+--------+--------------------+ | SORT_COL | ADDEND | RUNNING_SUM_MAX_15 | +----------+--------+--------------------+ | A | 3 | 3 | | B | 7 | 10 | | C | 6 | 16 | | D | 5 | 5 | | E | 9 | 14 | | F | 3 | 17 | | G | 8 | 8 | +----------+--------+--------------------+</code>
As evident, the conditional SUM is calculated correctly, with the running sum starting over after reaching 15.
The above is the detailed content of How to Calculate a Conditional SUM in Oracle with a Reset Threshold?. For more information, please follow other related articles on the PHP Chinese website!