// Because who needs duplicates, right?
WITH CTE AS (
SELECTDISTINCT key, category FROMtable)
//Over the partition, through the query, todistinct's house we go
SELECT
category, COUNT(key) OVER (PARTITION BY category) AS distinct_count
FROM CTE;
The magic of CTE comes into light. Deduplicating before counting provides a compact distinct count per category.
Advanced alternatives
Window of Opportunity with DENSE_RANK
// DENSE_RANK: like your average sports day, but for numbers
WITH Ranked AS (
SELECT key,
category,
DENSE_RANK() OVER (PARTITIONBY category ORDERBY key) AS dr
FROMtableWHERE key ISNOTNULL// Adds a classy touch of exclusivity
)
// Let the ranking games begin!SELECT category,
MAX(dr) AS distinct_count
FROM Ranked
GROUPBY category;
Aha! The quirky DENSE_RANK() roped in! The highest rank within each partition reflects a distinct count. But beware of Null values, unless they're invited guests at your count party.
SQL Server 2012 - Embracing the DISTINCT
In SQL Server 2012 and later, you can finally take your date COUNT(DISTINCT) to an OVER() function.
SELECT category,
COUNT(DISTINCT key) OVER (PARTITIONBY category) AS distinct_count
FROMtable;
// Welcome to the OUTER APPLY Club!No duplicates allowed
SELECT t.category,
dc.DistinctCount
FROM (SELECTDISTINCT category FROMtable) t
OUTER APPLY (
SELECTCOUNT(DISTINCT t2.key) AS DistinctCount
FROMtable t2
WHERE t2.category = t.category
) dc;
Correlated Subqueries - Your trusty sidekick
// Subqueries, the Robin to your Batman
SELECTDISTINCT category,
(SELECTCOUNT(DISTINCT key) FROMtable t2 WHERE t2.category = t1.category) AS distinct_count
FROMtable t1;
Grouping with Subqueries - A timeless classic
// Subqueries andGROUPBY go together like cookies and milk
SELECT category,
(SELECTCOUNT(DISTINCT key) FROMtable t2 WHERE t2.category = t1.category) AS distinct_count
FROMtable t1
GROUPBY category;
Advanced Techniques
Specific Counting Conditions
//Wheneverydistinct count must pass your Criteria
SELECT category,
COUNT(DISTINCTCASEWHENconditionTHEN key ELSENULLEND) OVER (PARTITIONBY category) AS conditional_distinct_count
FROMtable;
Aggregation Therapy
// Injecting some aggregation aspirin to alleviate your distinct count headaches
SELECT category,
(SELECTMIN(key) FROMtableWHERE category = t.category ANDcondition) AS conditional_distinct_count
FROMtable t
GROUPBY category;
explain-codes/Sql/Partition Function COUNT() OVER possible using DISTINCT