Partition Function COUNT() OVER possible using DISTINCT

后端 未结 4 1463
臣服心动
臣服心动 2020-11-27 10:26

I\'m trying to write the following in order to get a running total of distinct NumUsers, like so:

NumUsers = COUNT(DISTINCT [UserAccountKey]) OVER (PARTITION         


        
4条回答
  •  囚心锁ツ
    2020-11-27 11:03

    I use a solution that is similar to that of David above, but with an additional twist if some rows should be excluded from the count. This assumes that [UserAccountKey] is never null.

    -- subtract an extra 1 if null was ranked within the partition,
    -- which only happens if there were rows where [Include] <> 'Y'
    dense_rank() over (
      partition by [Mth] 
      order by case when [Include] = 'Y' then [UserAccountKey] else null end asc
    ) 
    + dense_rank() over (
      partition by [Mth] 
      order by case when [Include] = 'Y' then [UserAccountKey] else null end desc
    )
    - max(case when [Include] = 'Y' then 0 else 1 end) over (partition by [Mth])
    - 1
    

    An SQL Fiddle with an extended example can be found here.

提交回复
热议问题