SELECT DISTINCT values and count of that value from SQL table

I need a query that selects distinct values from a column and then the total number of occurrences of that value in the table.

COL1

2008
2008
2008
2009
2009
2010
2010
2010
2010
2010
2011
2011
2012
2013
2013
2013
2013
2013
2013

Expected result would be

RESULT
=======
2008 (3)
2009 (2)
2010 (5)
2011 (2)
2012 (1)
2013 (6)
Mike MillerSoftware EngineerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
It's a simple GROUP BY:

DECLARE @Sample TABLE ( COL1 INT ) ;

INSERT INTO @Sample
VALUES	( 2008 ),
	( 2008 ),
	( 2008 ),
	( 2009 ),
	( 2009 ),
	( 2010 ),
	( 2010 ),
	( 2010 ),
	( 2010 ),
	( 2010 ),
	( 2011 ),
	( 2011 ),
	( 2012 ),
	( 2013 ),
	( 2013 ),
	( 2013 ),
	( 2013 ),
	( 2013 ),
	( 2013 );

SELECT	COL1,
	COUNT(*)
FROM	@Sample
GROUP BY COL1;

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Kanti PrasadCommented:
Hi

SELECT COL1, count(*) AS count
FROM TableName
WHERE COL1 is not null
GROUP BY COL1;
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.