sql - Oracle SQL - 返回当前月份组中至少有一行并且上个月的班级发生变化的行
问题描述
我正在尝试输出满足以下条件的行:
- ClientID 的至少一行必须在当月(仅对当月 Client ID 的最新行感兴趣)
- ClientID 的当前月份的类与 ClientID 的前一个月的前一行不同
我的数据每个客户每月可以有多行,我只对每个客户每月的最新行感兴趣。
这是我的数据示例:
ID Client ID Class Date
14609 87415 C 04/DEC/18
13859 87415 X 16/AUG/18
11906 87415 C 27/FEB/17
10667 87415 B 23/JAN/17
14538 132595 D 03/DEC/18
14567 141805 C 04/DEC/18
14411 141805 A 27/NOV/18
基于上述的期望输出是:
ID Client ID Class Date
14609 87415 C 04/DEC/18
13859 87415 X 16/AUG/18
14567 141805 C 04/DEC/18
14411 141805 A 27/NOV/18
我对此进行了多次尝试,但成功率为零。任何帮助将不胜感激。我的尝试无法找到前一行。:/
select * from
(
select drh.defaultriskhistid, drh.clientid, cv.description,
drh.updatetimestamp
from default_risk_history drh
inner join code_values cv on drh.defaultriskcodeid = cv.codevalueid
where
defaultriskhistid in
(select max(defaultriskhistid) from default_risk_history
group by clientid, ltrim(TO_CHAR(updatetimestamp,'mm-yyyy'),'0'))
) t
where
(
Select count(*) from default_risk_history drh1 where drh1.clientid =
t.clientid and ltrim(TO_CHAR(drh1.updatetimestamp,'mm-yyyy'),'0') =
ltrim(TO_CHAR(current_date,'mm-yyyy'),'0')
) >=1
order by clientid, updatetimestamp desc
解决方案
您似乎想要最近的两行,如果它们有不同的类并且最近的行是在当前月份。如果是这样:
select t.*
from (select t.*,
max(date) over (partition by clientid) as max_date,
lag(class) over (partition by client_id order by date) as prev_class,
lead(class) over (partition by client_id order by date) as next_class,
row_number() over (partition by clientid order by date desc) as seqnum
from t
) t
where max_date >= trunc(sysdate, 'MON') and
( (seqnum = 1 and prev_class <> class) or
(seqnum = 2 and next_class <> class)
);
推荐阅读
- c - 数组 c 中的偶数和正数元素
- javascript - 从对象 javascript/typescript 数组更改属性名称
- javascript - 无法在 onEdit 函数中重新分配全局变量
- javascript - javascript 样式仅在使用 setTimeout 时应用于元素
- reactjs - 如何让我的 Ionic-React 应用程序停止更改 tsconfig.json 覆盖“JSX”类型?
- python - 为什么我在管理面板中创建的 Post 模型没有显示在管理面板中?
- javascript - 未捕获的类型错误:无法读取 chrome 未注册的 null 属性“classList”(试图显示和消失标题)
- python - 以 Python 变量为参数的 Shell 脚本
- python - 如何使用 xpath 创建循环?
- matlab - 错误:在 NSGA II 中,此操作的数组大小不兼容