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
 General SQL Server Forums
 New to SQL Server Programming
 Count Statement

Author  Topic 

dr223
Constraint Violating Yak Guru

444 Posts

Posted - 2012-04-10 : 09:25:05
Hi,

I have a table as;

IDno Code
1 Z
2 Z
3 X
4 X
5 X
6 Y
7 Y

I want to write a count of each code value and have the results as

X Y Z
3 2 2

Thank you

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2012-04-10 : 09:51:20
You can also do with CASE statements

DECLARE @Table TABLE(IdNo tinyint,Code char(1))
INSERT INTO @Table
VALUES
(1,'Z'),
(2,'Z'),
(3,'X'),
(4,'X'),
(5,'X'),
(6,'Y'),
(7,'Y')

SELECT [X],[Y],[Z]
FROM
(select IdNo,code
from @table
) p
PIVOT
(
Count(IDno) FOR Code in ([X],[Y],[Z])
) as pvt

Jim

Everyday I learn something that somebody else already knew
Go to Top of Page

dr223
Constraint Violating Yak Guru

444 Posts

Posted - 2012-04-10 : 09:54:03
thanks
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-04-10 : 15:24:27
hope your columns will be fixed!

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -