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

纵饮孤独 提交于 2020-01-02 03:26:06

问题


I have written this and successfully executed in Oracle

COUNT (DISTINCT APEC.COURSE_CODE) OVER (
                                            PARTITION BY s.REGISTRATION_NUMBER
                                            ,APEC.APE_ID
                                            ,COV.ACADEMIC_SESSION
                                            ) APE_COURSES_PER_ACADEMIC_YEAR

I'm trying to achieve the same result in SQL Server (our source database uses Oracle but our warehouse uses SQL Server).

I know the distinct isn't supported with window functions in SQL Server 2008 - can anyone suggest an alternative?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/27566568/count-distinct-value-over-partition-by-in-sql-server-2008

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