SQL-具有多个日期的条件窗口

SQL-具有多个日期的条件窗口,sql,apache-spark-sql,window,conditional-statements,Sql,Apache Spark Sql,Window,Conditional Statements,对于上表,我想计算过去x天内每位客户的投诉数量,并考虑投诉发生的时间。 i、 e.只有在交易日期之前发生投诉时,才应将其计算在内 i、 e 目前,如果投诉日期小于交易日期且交易日期在x天范围内,我正在使用客户、交易日期和投诉日期分区计算交易(记录)的数量,然后将其合并回客户和交易日期。 然后,我计算x天窗口内的最终金额,按客户划分,因为上面的结果是每个交易日期和客户的计数我认为您可以使用一个简单的where条件来实现这一点。假设日期字段以日期格式存储,计算过去10天(在SQL server中):

对于上表,我想计算过去x天内每位客户的投诉数量,并考虑投诉发生的时间。
i、 e.只有在交易日期之前发生投诉时,才应将其计算在内

i、 e

目前,如果投诉日期小于交易日期且交易日期在x天范围内,我正在使用客户、交易日期和投诉日期分区计算交易(记录)的数量,然后将其合并回客户和交易日期。
然后,我计算x天窗口内的最终金额,按客户划分,因为上面的结果是每个交易日期和客户的计数

我认为您可以使用一个简单的where条件来实现这一点。假设日期字段以日期格式存储,计算过去10天(在SQL server中):

这将产生以下输出:

;with tableA as
(select 'A' as customer,1 as Transaction_date,2 as Complaint_date union all
select 'A',1,3 union all
select 'A',2,3 union all
select 'B',1,2 union all
select 'B',1,2 union all
select 'B',2,3 union all
select 'C',2,3)

select a.Customer,a.transaction_date,count(b.Complaint_date) as cnt
from tableA a
left join tableA b on a.customer=b.customer
      and a.transaction_date>=b.Complaint_date
Group by a.Customer,a.transaction_date
如果需要与答案中所述相同的输出,可以将此输出连接回原始表:

Customer Transaction_Date Cnt
A        1                0
A        2                1
B        1                0
B        2                2
C        2                0

不完全是这样,这将给出一个0的计数,因为投诉日期永远不会少于交易日期。如果投诉发生在交易日期之前,则应将其计算在内,您的意思是什么?您是否希望交叉引用所有记录?确切地说,我需要每个客户和日期的计数以及一个窗口功能我为您的要求添加了一个编辑功能…这是否提供了您要查找的内容?我需要每个客户和交易日期的计数,我认为如果没有一个窗口功能,就不能用你正在使用的数据库标记你的问题。日期真的是数字吗?
select Customer,count(*)
from table 
where Complaint_date<transaction_date
      and Complaint_date between GETDATE()-10 and GETDATE()
Group by Customer
;with tableA as
(select 'A' as customer,1 as Transaction_date,2 as Complaint_date union all
select 'A',1,3 union all
select 'A',2,3 union all
select 'B',1,2 union all
select 'B',1,2 union all
select 'B',2,3 union all
select 'C',2,3)

select a.Customer,a.transaction_date,count(b.Complaint_date) as cnt
from tableA a
left join tableA b on a.customer=b.customer
      and a.transaction_date>=b.Complaint_date
Group by a.Customer,a.transaction_date
Customer Transaction_Date Cnt
A        1                0
A        2                1
B        1                0
B        2                2
C        2                0
;with tableA as
(select 'A' as customer,1 as Transaction_date,2 as Complaint_date union all
select 'A',1,3 union all
select 'A',2,3 union all
select 'B',1,2 union all
select 'B',1,2 union all
select 'B',2,3 union all
select 'C',2,3)

select x.*,y.cnt
from tableA x
inner join
(select a.Customer,a.transaction_date,count(b.Complaint_date) as cnt
from tableA a
left join tableA b on a.customer=b.customer
      and a.transaction_date>=b.Complaint_date
Group by a.Customer,a.transaction_date) y
ON x.customer=y.customer and x.transaction_date=y.Transaction_date