Blog Stats
  • Posts - 59
  • Articles - 0
  • Comments - 31
  • Trackbacks - 0

 

tsql: Counting unique elements in a sql server table

Today I wanted to count each unique element in a SQL Server table to make sure they were unique.  Took a bit of playing but this finally works great:

SELECT DISTINCT t.columntocheck, (Select COUNT(columntocheck) from tabletoserach where columntocheck = t.columntocheck) as countof
FROM tabletoserach t

This gives me back a list of all unique items in columntocheck and also counts the number of them.

Of course, theres no where clause on this so be careful if you have a huge table. Mine was really small, so this works just fine.


Feedback

# re: tsql: Counting unique elements in a sql server table

Gravatar Duh!

Why do you have to do this? Isn't simpler and has better performance to do the following?

SELECT columntocheck, COUNT(*)
FROM tabletoserach
GROUP BY columntocheck
8/9/2011 10:34 AM | Nicholas K

# re: tsql: Counting unique elements in a sql server table

Gravatar The COUNT function returns the number of rows that matches a specified definition and the DISTINCT statement can be used to return only distinct values. -Dr. Naveed Fazlani 12/19/2011 7:59 AM | Bryan Keith

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

 

 

Copyright © xamlnotes