sql - 用于循环记录的 SQL 查询
问题描述
我有一张包含一百万条记录的表。这是带有一些示例数据点的表格结构 -
patient claim thru_dt cd start
322 65 20200201 42 20181008
322 65 20200202 42
322 95 20200203 52
122 05 20200105 23
122 05 20200115 42 20190102
122 05 20200116 42
我需要编写一个会产生此输出的查询 -
patient claim thru_dt cd start
322 65 20200201 42 20181008
322 65 20200202 42 20181008
322 95 20200203 52 20181008
122 05 20200105 23
122 05 20200115 42 20190102
122 05 20200416 42
给出患者 322 的第二个声明的原因20181008
是因为第一个和第二个具有相同的cd
值。
患者 322 的第三次索赔也被赋予了20181008
价值,即使它没有相同的cd
价值,因为它是患者的最后一次索赔。
患者 122 的第一个声明仍然为 NULL 的原因是该声明的cd
值不等于 42。
患者 122 的第三次索赔20190102
即使具有相同的cd
值也没有被赋予值的原因是因为他们先前索赔中的 thru_dt 相隔超过 30 天。
这是我迄今为止尝试过的 -
--This orders claims using row_number
DECLARE @min_record int;
DECLARE @max_record int;
select
@min_record = MIN(row_num),
@max_record = MAX(row_num)
from
(
select *,
row_number() over(partition by patient order by thru_dt) as row_num
from
table
)
while @min_record <= @max_record
begin
--Logic I need help with
SET @min_record = @min_record + 1
end
解决方案
我认为横向连接和条件表达式可以更简单地实现您想要的逻辑:
select t.*,
case
when t.start is null and (
s.cd = t.cd
or row_number() over(partition by t.patient order by t.thru_dt desc) = 1
)
then s.start
else t.start
end new_start
from mytable t
outer apply (
select top (1) s.*
from mytable s
where
s.patient = t.patient
and s.start is not null
and s.thru_dt >= dateadd(day, -30, t.thru_dt)
order by s.thru_dt desc
) s
order by patient desc, thru_dt
病人 | 索赔 | thru_dt | 光盘 | 开始 | 新的开始 ------: | ----: | :--------- | -: | :--------- | :--------- 322 | 65 | 2020-02-01 | 42 | 2018-10-08 | 2018-10-08 322 | 65 | 2020-02-02 | 42 | 空 | 2018-10-08 322 | 95 | 2020-02-03 | 52 | 空 | 2018-10-08 122 | 5 | 2020-01-05 | 23 | 空 | 无效的 122 | 5 | 2020-01-15 | 42 | 2019-01-02 | 2019-01-02 122 | 5 | 2020-04-16 | 42 | 空 | 无效的
推荐阅读
- java - 使用 for 循环从列表中删除电影。For循环工作一次然后抛出索引超出范围异常
- node.js - 如何在firebase-functions上使用firebase.auth().signInWithEmailAndPassword作为带有nodejs的API?
- c# - 如何使用 VB.net 中的流线器将我的数组写入 txt 文件
- excel - 检查文本并添加多个工作表列
- ms-office - MsoTriState 有什么用?使用 VBA 添加图片有多重要?
- google-api - Google API 导入自然语言数据集导入不起作用
- javascript - React 表单中 event.preventDefault 的事件未定义
- apscheduler - 如何在 cron 语句中将 5 个参数表达式扩展为 7 个参数表达式
- c# - 一段时间后无法连接到服务器
- javascript - 如何修复“未捕获的类型错误:无法读取 null 的属性‘点击’”