sql - 每当业务发生变化时标记
问题描述
数据#TRAN
ID Business STDT
501 50005038 20170208
501 50005038 20170801
501 50005035 20170802
501 50005038 20171101
501 50005038 20180101
501 50005035 20180201
514 50005038 20170208
514 50005038 20170423
514 50005038 20170801
514 50005038 20170801
514 50005035 20170802
514 50005038 20171101
514 50005035 20171201
我正在尝试标记那些业务代码正在更改的事件。我尝试了下面提到的查询,但是我得到的结果也显示了以前的业务代码。我想要只标记更改的业务代码行的查询
我试过这个查询
代码:
with cte as
(
select *, ROW_NUMBER() over(partition by ID order by STDT) as rn
from #TRAN
)
,cte1 as
(
select c1.ID, c1.Business as S1, c1.STDT as T1, c2.Business as S2, c2.STDT as T2, c1.[], c1.
from cte c1 join cte c2
on c1.rn + 1 = c2.rn
and c1.ID = c2.ID
where c1.Business <> c2.Business
)
select ID,[], ,
case n
when 1 then S1
when 2 then S2
end as Business_Code,
case n
when 1 then T1
when 2 then T2
end as Timestamp
from cte1 cross join (select 1 n union all select 2) nums
order by ID, [Timestamp];
结果我得到-->
ID Business Timestamp
501 50005038 20170801
501 50005035 20170802
501 50005035 20170802
501 50005038 20171101
501 50005038 20180101
501 50005035 20180201
514 50005038 20170801
514 50005035 20170802
514 50005035 20170802
514 50005038 20171101
514 50005038 20171101
结果我想要-->
ID Business STDT Flag
501 50005038 20170208
501 50005038 20170801
501 50005035 20170802 1
501 50005038 20171101 1
501 50005038 20180101
501 50005035 20180201 1
514 50005038 20170208
514 50005038 20170423
514 50005038 20170801
514 50005038 20170801
514 50005035 20170802 1
514 50005038 20171101 1
514 50005035 20171201 1
解决方案
GMB 的回答很好,但可以简化为:
select t.*,
(case when business = lag(business) over (partition by id order by stdt)
then null else 1
end) as flag
from mytable t;
推荐阅读
- loops - Java-“For”循环条件以用户输入结束
- python - Python:读取完整的 .js 文件并更新该 js 文件中的特定方法
- autolayout - 在情节提要中选择 UILabel 时,它周围的白色区域是什么?
- binary - 我正在增加 CPU 代码中的程序计数器,它在继续之前停在六个及其倍数几个周期
- python - 如何在不使用 cv2.warpAffine() 的情况下翻译图像?[Python 3 和 OpenCV 4.1]
- flutter - “位置参数必须出现在命名参数之前。尝试在命名参数之前移动所有位置参数”错误颤动
- php - 使用 Gravity Forms 更改 PHP 过滤器以返回提交的值而不是字段名称
- javascript - phantomjs+express 不工作并出现错误
- c# - SoapCore 错误
- python - Pandas 按不同列查找(一次一个)