简体   繁体   中英

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

This is the sample expected result table

在此处输入图片说明

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

在此处输入图片说明

Any help will be greatly appreciated :)

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:

在此处输入图片说明

If you want:

select tenantcode,  b.name, AreaSqm ,
       COUNT(DISTINCT areasqm) OVER (PARTITION BY tenantcode) AS acnt
from TENANT;

Then you can do this without an aggregation/join. You simply need to enumerate the values and count where they are equal to 1:

select tenantcode, name, AreaSqm,
       sum(case when seqnum = 1 then 1 else 0 end) over (partition by tenantcode) as acnt
from (select t.*,
             row_number() over (partition by tenantcode, areasqm order by tenantcode) as seqnum
      from TENANT t
     ) t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM