Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Hi first time poster hereI 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 valuesI tried:select count(*) from Table group by Valueand 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 TableGROUP BY Value??
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 hereI 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 valuesI tried:select count(*) from Table group by Valueand 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 @tempSELECT t1.CatId,t1.colcount,t2.distcount FROM(SELECT CatId,COUNT(*) as 'colcount'FROM @tempGROUP BY CatId)t1CROSS JOIN (SELECT COUNT(DISTINCT CatId) AS 'DistCount' FROM @temp)t2output--------------------------------------Inserted dataID CatId----------- -----------1 12 33 24 45 26 47 28 19 3--resultCatId colcount distcount----------- ----------- -----------1 2 42 3 43 2 44 2 4