提问人:WanderingMushroom 提问时间:10/17/2023 最后编辑:MT0WanderingMushroom 更新时间:10/17/2023 访问量:45
我想找到每次子猫更改或返回时的第一个日期,特定子猫可能会被报告不止一次 [重复]
I want to find the first date for each time a subcat changes or back again, a particular sub cat might be reported more than once [duplicate]
问:
在 oracle DB 上工作。我有以下数据
客户 | 类别 | 子领域 | 日期 |
---|---|---|---|
1 | 饲料 | 微 丸 | 05 10月,23 |
1 | 饲料 | 干草 | 18 9月,23 |
1 | 饲料 | 微 丸 | 06-8月,23 |
1 | 饲料 | 微 丸 | 04-七月,23 |
1 | 饲料 | 微 丸 | 21-Jun_23 |
1 | 辅料 | 铅 | 15 5月,23 |
1 | 辅料 | 铅 | 01-Mar_23 |
对于每个客户和类别,我想要他们每次返回子类别时的第一个日期。例如,在 6 月 21 日首先购买了颗粒,然后在那之后又购买了几次,然后他们改用干草 - 所以我们将报告该生产线,然后返回颗粒,所以再次想要该生产线。因此,提取
客户 | 类别 | 子领域 | 日期 |
---|---|---|---|
1 | 饲料 | 微 丸 | 05 10月,23 |
1 | 饲料 | 干草 | 18 9月,23 |
1 | 饲料 | 微 丸 | 21-Jun_23 |
1 | 辅料 | 铅 | 01-Mar_23 |
从以上数据来看
最小组 by 不起作用,因为它只会给我子类别的第一个实例,我想要每次他们返回子类别时的第一个日期。
看看这里的其他问题,我虽然分区可能会有所帮助,但我似乎无法让它正常工作。也许排名属于某个地方?
我觉得对于知道自己在做什么的人来说,这真的很容易和明显,但显然这不是我,因为我只走了几步 select *......
提前感谢您的任何帮助。
答:
2赞
SelVazi
10/17/2023
#1
你有一个问题,你可以利用两个row_numbers之间的差异来为每组连续的行提供一个唯一的 id:gaps and islands
with cte as (
select Customer,
Category,
Subcategory,
purchase_date,
row_number() over (partition by Customer, Category order by purchase_date) -
row_number() over (partition by Customer, Category, Subcategory order by purchase_date) as grp
from mytable
)
select CUSTOMER, CATEGORY, SUBCATEGORY, min(PURCHASE_DATE) as PURCHASE_DATE
from cte
group by CUSTOMER, CATEGORY, SUBCATEGORY, grp
order by CUSTOMER, CATEGORY desc, PURCHASE_DATE desc
评论