Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Count a Field

Author  Topic 

ckuo@kahluadesigns.com
Yak Posting Veteran

58 Posts

Posted - 2002-10-30 : 17:00:59
Hi,
Say I have

TABLE
ID---------Name-----Category
1----------Test1----Car
2----------Test2----Car
3----------Test3----Car
4----------Test4----Motorcycle
5----------Test5----Motorcycle

I would like to return
ID---------Name-----Category-----CountCategory
1----------Test1----Car----------3
2----------Test2----Car----------3
3----------Test3----Car----------3
4----------Test4----Motorcycle---2
5----------Test5----Motorcycle---2

How would I get the CountCategory?

Thanks

tool
Starting Member

26 Posts

Posted - 2002-10-30 : 17:36:35
Here's two ways:


SELECT ID, Name, Category,
(SELECT COUNT(Category) FROM MyTable WHERE Category=t.Category) AS CountCategory
FROM MyTable t


OR


SELECT t.ID, t.Name, t.Category, CountCategory
FROM MyTable t INNER JOIN
(SELECT Category, COUNT(Category) AS CountCategory FROM MyTable GROUP BY Category) AS c
ON t.Category = c.Category

Go to Top of Page
   

- Advertisement -