Click here to Skip to main content
16,019,876 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I have a Database with a Column with value containing 0 to 5 example as shown below :

IndeX     Name     Status
  1       Test       0
  1       Test       3
  1       Test       1
  1       Test       0
  1       Test       2
  1       Test       1
  1       Test       5
  1       Test       0



I Want to count the number of each number inside Status and insert into another table the output i want is shown below

Index   Zero   One    Two    Three    Four    Five
 1        3     2      1      1        0       1


What is the SQL statement to achieve this ?

[edit]Code block added, "Ignore HTML..." option disabled, minor spelling and punctuation - OriginalGriff[/edit]
Posted
Updated 6-Mar-11 20:38pm
v2

You can use pivot operator to this. Please check the following tutorial:

http://msdn.microsoft.com/en-us/library/ms177410.aspx[^]
 
Share this answer
 
You can get required output with some sub-query like below

SQL
select
SC.MyIndex AS Index1,
(SELECT count(sc1.status) as z FROM statuscount SC1 WHERE sc1.status = 0 group by sc1.myindex,sc1.status ) AS ZERO,
(SELECT count(sc1.status) as o FROM statuscount SC1 WHERE sc1.status = 1 group by sc1.myindex,sc1.status ) AS One,
(SELECT count(sc1.status) as t FROM statuscount SC1 WHERE sc1.status = 2 group by sc1.myindex,sc1.status ) AS TWO,
(SELECT count(sc1.status) as th FROM statuscount SC1 WHERE sc1.status = 3 group by sc1.myindex,sc1.status ) AS Three,
(SELECT count(sc1.status) as fo FROM statuscount SC1 WHERE sc1.status = 4 group by sc1.myindex,sc1.status ) AS Four,
(SELECT count(sc1.status) as fi FROM statuscount SC1 WHERE sc1.status = 5 group by sc1.myindex,sc1.status ) AS Five
FROM  statuscount SC group by sc.myindex



Another solution in different form is

SQL
select
sc.MyIndex,sc.status,count(sc.status) AS TotalCount from statuscount SC group by sc.myindex,sc.status


Hope it helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900