sql - Oracle上的条件SUM

标签 sql oracle oracle12c oracle-analytics

我正在尝试使用条件和进行查询。重置后,SUM需要大于15。像这样:

A | 3 | 3 
B | 7 | 10 
C | 6 | 16  -- ====
D | 5 | 5 
E | 9 | 14
F | 3 | 17  -- ====
G | 8 | 8
我该怎么做?

最佳答案

作为递归SQL的替代方法,您还可以使用SQL MODEL子句。就个人而言,尽管很难编写(因为像我一样的大多数人都需要查找语法),但我发现它比递归SQL易读。

-- "test_data" is just a substitute for your real table, which I don't have
-- it is just so people without your table can run this example and would
-- not be part of your real solution.
with test_data ( sort_col, addend ) as
( SELECT 'A', 3 FROM DUAL UNION ALL
 SELECT 'B', 7 FROM DUAL UNION ALL
 SELECT 'C', 6 FROM DUAL UNION ALL
 SELECT 'D', 5 FROM DUAL UNION ALL
 SELECT 'E', 9 FROM DUAL UNION ALL
 SELECT 'F', 3 FROM DUAL UNION ALL
 SELECT 'G', 8 FROM DUAL ),
-- Solution begins here
sorted_inputs ( sort_col, sort_order, addend, running_sum_max_15) as
( SELECT sort_col, row_number() over ( order by sort_col ) sort_order, addend, 0 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],
  running_sum_max_15[sort_order>1] = 
          case when running_sum_max_15[CV(sort_order)-1] < 15 THEN 
             running_sum_max_15[CV(sort_order)-1] ELSE 0 END+addend[CV(sort_order)]
)

结果
+----------+--------+--------------------+
| 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 |
+----------+--------+--------------------+

关于sql - Oracle上的条件SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52936012/

相关文章:

sql - 查询选择计数(*)和列

json - 如何使用 Oracle 12C JSON_VALUE 提取大于 4000 字节的 json 值?

Oracle 游标的返回类型

sql - SQL (Oracle) 中的递归计算

oracle - 使用 Oracle 数据库的 JOIN 语法更新

oracle - ORA-65096 : invalid common user or role name while installing data miner repository

http - 如何在OSB中为HTTP后端服务实现选择性错误重试

php - 我在处理数据时是否需要锁定我的记录以避免不一致?

sql - 使用 DateDiff 查找持续时间(以分钟为单位)

sql - 如何在Hbase中进行反规范化?