Search code examples
sqlsql-server-2008database-partitioning

SQL SERVER QUERY to get the Number of Distinct column in table


This is the sample expected result table

enter image description here

As you can see I have a list of tenant with corresponding Area. I need to create a column 'Count' where it will count the number of distinct Area in the given TENANT. For example tenant 'CMBINA13' has two distinct Area. So it should output 2 in the count column, same with the next tenant example having 1 distinct area only.

Here's what I have initially got

select tenantcode ,  b.name , AreaSqm  ,
       COUNT(*) OVER (PARTITION BY AreaSqm) AS 'Count'
from    TENANT

and it gives a logically incorrect output like this

enter image description here

Any help will be greatly appreciated :)


Solution

  • You have to count DISTINCT areasqm, but you can't do this with COUNT .. OVER, and you can't do it neither with GROUP BY tenantcode , name , AreaSqm directly. So, one solution is to count DISTINCT areasqm in a subquery, something like this:

    SELECT
      t.tenantcode , name , AreaSqm  , c.areaCount
    FROM TENANT AS t
    INNER JOIN
    (
       SELECT tenantcode, COUNT(DISTINCT areasqm) AS areaCount
       FROM tenant 
       GROUP BY tenantcode
    ) AS c ON t.tenantcode = c.tenantcode;
    

    This will give you:

    enter image description here