Count (Distinct ([value)) OVER (Partition by) in SQL Server 2008

人走茶凉 提交于 2019-12-05 07:27:23

Here's what I recently came across. I got it from this post. So far it works really well for me.

DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields ASC) +
DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields DESC) - 1 AS DistinctCount

Alas, you cannot do count(distinct) over in SQL Server. You can do this with a subquery. The idea is to enumerate the values within each course code (and subject to the other partitioning conditions). Then, just count up the values where the sequence number is 1:

select sum(case when cc_seqnum = 1 then 1 else 0 end) as APE_COURSES_PER_ACADEMIC_YEAR
from (select . . . ,
             row_number () OVER (PARTITION BY s.REGISTRATION_NUMBER, APEC.APE_ID,
                                              COV.ACADEMIC_SESSION,
                                              APEC.COURSE_CODE
                                 ORDER BY (SELECT NULL)
                                ) as cc_seqnum
      from . . . 
     ) t

You have a complex query. I would suggest that you replace the count(distinct) with the row_number() and make your current query a subquery or CTE for the final query.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!