Kob*_*mit 4 sql oracle analytics
我已将电子表格中的数据(“金额”和“收入”)导入表格中,并且需要查询的帮助,以便根据其“收入”将连续记录分组。例如:
预期产量:
line_no amount narration calc_group <-Not part of table
----------------------------------------
1 10 Reason 1 1
2 -10 Reason 1 1
3 5 Reason 2 2
4 5 Reason 2 2
5 -10 Reason 2 2
6 -8 Reason 1 3
7 8 Reason 1 3
8 11 Reason 1 3
9 99 Reason 3 4
10 -99 Reason 3 4
Run Code Online (Sandbox Code Playgroud)
我尝试了一些分析功能:
line_no amount narration calc_group <-Not part of table
----------------------------------------
1 10 Reason 1 1
2 -10 Reason 1 1
3 5 Reason 2 2
4 5 Reason 2 2
5 -10 Reason 2 2
6 -8 Reason 1 3
7 8 Reason 1 3
8 11 Reason 1 3
9 99 Reason 3 4
10 -99 Reason 3 4
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为第6至8行的旁白与第1行和第2行相同。
line_no amount narration calc_group
----------------------------------------
1 10 Reason 1 1
2 -10 Reason 1 1
3 5 Reason 2 3
4 5 Reason 2 3
5 -10 Reason 2 3
6 -8 Reason 1 1
7 8 Reason 1 1
8 11 Reason 1 1
9 99 Reason 3 4
10 -99 Reason 3 4
Run Code Online (Sandbox Code Playgroud)
我已经设法使用滞后分析功能和序列来做到这一点,虽然它不是很优雅,但是可以工作。应该有更好的方法,请发表评论!
select line_no, amount, narration,
first_value (line_no) over
(partition by narration order by line_no) "calc_group"
from test
order by line_no
Run Code Online (Sandbox Code Playgroud)
我对更好的答案感到满意。谢谢kordiko!
试试这个查询:
SELECT line_no,
amount,
narration,
SUM( x ) OVER ( ORDER BY line_no
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) as calc_group
FROM (
SELECT t.*,
CASE lag( narration ) OVER (order by line_no )
WHEN narration THEN 0
ELSE 1 END x
FROM test t
)
ORDER BY line_no
Run Code Online (Sandbox Code Playgroud)
演示-> http://www.sqlfiddle.com/#!4/6d7aa/9
归档时间: |
|
查看次数: |
3517 次 |
最近记录: |