sql - 根据列 oracle 中的数据定义组
问题描述
我在 col 1 中有一个带有 oracle 序列的表,我需要根据 col 2 中的值进行分组。下面是带有数据的示例表。数据库版本 = Oracle 12.1
分组的条件是 col2 应该有 50,或者如果它有 30,那么下一个 50 应该属于同一组。不能一个人有30个,后面会有50个
我写了以下内容,但没有得到预期的结果
SELECT col1,col2,count(CASE WHEN col2 in (30,50) THEN 1 END)OVER(ORDER BY col1) from table.
最后我需要最高组,这是可行的。
Col1 Col2 Expected output Grp
----- ----- -------------------
1 3
2 50 1
3 10
4 2
5 30 2
6 12
7 50 2
8 14
9 50 3
10 50 4
解决方案
嗯。. . 我认为逻辑是这样的:
select t.*,
sum(case when col2 = 50 and
(prev_30 is null or prev_30 < prev_50)
then 1 else 0
end) over (order by col1) as grp
from (select t.*,
lag(case when col2 = 50 then col1 end ignore nulls) over (order by col1) as prev_50,
lag(case when col2 = 30 then col1 end ignore nulls) over (order by col1) as prev_30
from t
) t;
我们的想法是获取col1
“50”和“30”的先前值,我们可以使用ignore null
s 选项lag()
(或使用累积条件最大值)来做到这一点。
那么定义组的逻辑是开始每个组的“50”的累积总和。
推荐阅读
- javascript - 您将如何使用 Discord.js 创建一个每天运行的活动?
- laravel - Laravel 计数多级分组
- php - 从 Lavarel App 的 url 中删除 public/index.php
- validation - 如何为 Xamarin 应用程序创建离线验证系统?
- excel - 在 VBA 中使用复制目标代码仅复制值而不是公式
- selenium - selenium.common.exceptions.InvalidArgumentException:消息:找不到文件:尝试上传文件夹时
- android - 国际化应用标题
- c# - 如何将静态路由添加到运行可执行文件时仍然有效的桌面应用程序?
- xml - 使用 XSLT 转换修改后的 Dublin Core XML
- java - 排除和重新导入不同版本的 Maven 依赖项