我想计算不同的yyyydd
超过mm
(日期)。 (+- 2 天)
但是,distinct 函数不能与 over 一起使用。
如果我删除不同的,它会给我总计数yyyydd
, but yyyydd
可以有很多重复的。这就是为什么我想添加不同的。
这有点类似于count(distinct) over (partition by... 在 Oracle SQL 中不起作用 https://stackoverflow.com/questions/55347200/countdistinct-over-partition-by-doesnt-work-in-oracle-sql但不同:(
with tbl1 as
(select 'tay' cst_name, 'toy1' product_name, '20230501' yyyymmdd from dual union all
select 'tay' cst_name, 'toy1' product_name, '20230502' yyyymmdd from dual union all
select 'tay' cst_name, 'toy1' product_name, '20230507' yyyymmdd from dual union all
select 'ray' cst_name, 'toy2' product_name, '20230321' yyyymmdd from dual union all
select 'ray' cst_name, 'toy2' product_name, '20230421' yyyymmdd from dual union all
select 'ray' cst_name, 'toy2' product_name, '20230422' yyyymmdd from dual union all
select 'ray' cst_name, 'toy1' product_name, '20230423' yyyymmdd from dual union all
select 'ray' cst_name, 'toy1' product_name, '20230423' yyyymmdd from dual union all
select 'ray' cst_name, 'toy1' product_name, '20230527' yyyymmdd from dual union all
select 'ray' cst_name, 'toy2' product_name, '20230527' yyyymmdd from dual )
,
tbl2 as(
select a.*, substr(yyyymmdd,1,6) as yyyymm, substr(yyyymmdd ,7,9) as mm
from tbl1 a)
select
b.*
, count(1) over (partition by cst_name, product_name order by to_number(mm) range between 2 preceding and 2 following) as cnt
, count(distinct yyyymm) over (partition by cst_name, product_name order by to_number(mm) range between 2 preceding and 2 following) as cnt -- error
from tbl2 b
cst_name |
prod_name |
yyyyddmm |
mm |
cnt(wrong) |
cnt(wanted) |
tay |
toy1 |
20230501 |
01 |
2 |
1 |
tay |
toy1 |
20230502 |
02 |
2 |
1 |
tay |
toy1 |
20230507 |
07 |
1 |
1 |
ray |
toy2 |
20230321 |
21 |
3 |
2 |
ray |
toy2 |
20230421 |
21 |
3 |
2 |
ray |
toy2 |
20230422 |
22 |
3 |
2 |
ray |
toy1 |
20230423 |
23 |
2 |
1 |
ray |
toy1 |
20230423 |
23 |
2 |
1 |
ray |
toy1 |
20230527 |
27 |
1 |
1 |
ray |
toy2 |
20230527 |
27 |
1 |
1 |