是否有办法在日期范围内的每一行上进行density_rank()处理?

时间:2019-04-15 04:32:15

标签: sql-server window-functions dense-rank

我正在尝试在具有ID号且日期在过去12个月内的列中获取唯一商品的计数。我需要遍历表中的每一行。

我正在使用density_rank()和(Over partition by的组合来计算唯一项目的数量,但是我无法成功添加日期过滤器。到目前为止,我看到的结果显示的是不论日期如何,具有相同ID的每一行都具有唯一的Unique_Code。

select ID, 
       Unique_Code, 
       Transaction_Date,  
       DATEADD(Month, -12, Transaction_Date) as L12M,
       dense_rank() over (partition by ID order by Transaction_Date, Unique_Code) as [Unique_Count]
            from (select *, (case when datediff(day, lag(Transaction_Date,1,Transaction_Date) over (partition by Unique_Code order by ID), Transaction_Date)
             <= 1 
                      then 1 else 2 
                 end) as grp
      from datatable1)

我希望结果显示对行中id的unique_code列中的唯一项计数,并且同一ID内的先前条目的交易日期和交易日期为12个月。现在,无论日期范围如何,我都从每个具有相同ID的条目的unique_code列中看到了唯一项的计数。

Table of expected results

1 个答案:

答案 0 :(得分:0)

很遗憾,我没有要测试的源数据,但是,我在下面为您添加了一个额外的列:

select
    ID
,   Unique_Code
,   Transaction_Date
,   DATEADD(Month, -12, Transaction_Date) as L12M
,   dense_rank() over (partition by ID order by Transaction_Date, Unique_Code) as [Unique_Count]
,   rank() over (partition by Transaction_Date order by ID) NewUniqueCount
from (select *, (case   when datediff(day, lag(Transaction_Date,1,Transaction_Date) over (partition by Unique_Code order by ID), Transaction_Date) <= 1 
                        then 1 else 2 end) as grp from datatable1)

让我知道它是否有效吗? -应该可以。