Window functions to count distinct records

前端 未结 3 505
没有蜡笔的小新
没有蜡笔的小新 2020-12-23 15:08

The query below is based on a complicated view and the view works as I want it to (I\'m not going to include the view because I don\'t think it will help with the question a

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 15:53

    I came across this question in search for a solution to my problem of counting distinct values. In searching for an answer I came across this post. See last comment. I've tested it and used the SQL. It works really well for me and I figured that I would provide another solution here.

    In summary, using DENSE_RANK(), with PARTITION BY the grouped columns, and ORDER BY both ASC and DESC on the columns to count:

    DENSE_RANK() OVER (PARTITION BY drugClass ORDER BY drugName ASC) +
    DENSE_RANK() OVER (PARTITION BY drugClass ORDER BY drugName DESC) - 1 AS drugCountsInFamilies
    

    I use this as a template for myself.

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

    I hope this helps!

提交回复
热议问题