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
 SQL Server Development (2000)
 SQL to get value counts

Author  Topic 

leosuth
Starting Member

5 Posts

Posted - 2008-01-31 : 11:55:40
Hi first time poster here

I have a table Table (say) with a field Value that has a number of rows such that field Value has a variety of values (lets say they are integers).

Could someone give me the SQL query to return the number of different values in Value, and also the number of occurences in Value of those different values

I tried:

select count(*) from Table group by Value

and this effectively gave the second bit of info I asked for - I really want if possible a single query to cover both and not sure how to address this.

Much appreciated

jdaman
Constraint Violating Yak Guru

354 Posts

Posted - 2008-01-31 : 11:58:02
SELECT Value, COUNT(*)
FROM Table
GROUP BY Value
??
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-01-31 : 23:50:31
quote:
Originally posted by leosuth

Hi first time poster here

I have a table Table (say) with a field Value that has a number of rows such that field Value has a variety of values (lets say they are integers).

Could someone give me the SQL query to return the number of different values in Value, and also the number of occurences in Value of those different values

I tried:

select count(*) from Table group by Value

and this effectively gave the second bit of info I asked for - I really want if possible a single query to cover both and not sure how to address this.

Much appreciated



i think this is what you are looking at:-


declare @temp table
(ID int IDENTITY(1,1),
CatId int
)

Insert into @temp (CatID) values (1)
Insert into @temp (CatID) values (3)
Insert into @temp (CatID) values (2)
Insert into @temp (CatID) values (4)
Insert into @temp (CatID) values (2)
Insert into @temp (CatID) values (4)
Insert into @temp (CatID) values (2)
Insert into @temp (CatID) values (1)
Insert into @temp (CatID) values (3)

select * from @temp

SELECT t1.CatId,t1.colcount,t2.distcount FROM
(
SELECT CatId,COUNT(*) as 'colcount'
FROM @temp
GROUP BY CatId)t1
CROSS JOIN (SELECT COUNT(DISTINCT CatId) AS 'DistCount'
FROM @temp)t2

output
------------------------------------
--Inserted data
ID CatId
----------- -----------
1 1
2 3
3 2
4 4
5 2
6 4
7 2
8 1
9 3


--result
CatId colcount distcount
----------- ----------- -----------
1 2 4
2 3 4
3 2 4
4 2 4
Go to Top of Page

leosuth
Starting Member

5 Posts

Posted - 2008-02-01 : 09:56:34
Thanks guys, that did the trick
Go to Top of Page
   

- Advertisement -