简体   繁体   中英

How to get the number of distinct records in a SQL Server 2008 database?

I have a table with users. Each user has a country row filled in (no user without a country).

How can i get the number of countries that has a user?

select distinct Country_CountryId 
from users

This returns a list with all different countries (their id from the country table). But how can I sum them into an int without getting all entries back to my MVC controller and then count them there.

I tried

select distinct count(Country_CountryId) 
from users

But that does not return a correct answer.

Example: table has 4 users.

  • User 1: UK
  • User 2: UK
  • User 3: US
  • User 4: Spain

This should result in a count of 3 distinct countries

Try this:

select
    count( distinct Country_Country_Id ) 
from users

The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column

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