我正试图编写一个查询,从每个组中查找第一个最近的1,如下所示。例如,对于第1组,它不应该是2022年2月1日,因为它有2022年6月1日(稍后显示(。第一组不应该是2022年1月7日。
如果你有任何想法,请告诉我。
谢谢!
Table x (AsOfDate, Group_Id, Value)
AsOfDate Group_Id Value
1/1/2022 1 0
1/1/2022 2 1
1/2/2022 1 1
1/2/2022 2 1
1/3/2022 1 0
1/3/2022 2 0
1/4/2022 1 0
1/4/2022 2 0
1/5/2022 1 0
1/5/2022 2 1
1/6/2022 1 1
1/6/2022 2 0
1/7/2022 1 1
1/7/2022 2 0
Output
AsOfDate Group_Id
1/6/2022 1
1/5/2022 2
您想要的是找到具有Value = 1
的连续行的最后一组的最早日期
使用LAG()
窗口函数查找Value
的连续组
使用dense_rank()
按grp
对其进行排序,找到最新的组(r = 1
(
CCD_ 7以得到";第一个";AsOfDate
select AsOfDate = min(AsOfDate),
Group_Id
from
(
select *, r = dense_rank() over (partition by Group_Id, Value
order by grp desc)
from
(
select *, grp = sum(g) over (partition by Group_Id order by AsOfDate)
from
(
select *, g = case when Value <> lag(Value) over (partition by Group_Id
order by AsOfDate)
then 1
else 0
end
from x
) x
) x
) x
where Value = 1
and r = 1
group by Group_Id