sql count

I want the result return like

count_B   count_X   count_S   count_N  
  2                    1           1                1

This is my sample table.

select status_sent from mytable

status_sent
B
X
S
N
B
VBdotnet2005Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

x-menIT super heroCommented:
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(Status_sent)
  FROM (SELECT p.Status_sent FROM dbo.ee AS p
  GROUP BY p.status_sent) AS x;
SET @sql = N'
SELECT ' + STUFF(@columns, 1, 2, '') + '
FROM
(
  SELECT p.Status_sent
   FROM dbo.EE AS p
) AS j
PIVOT
(
  count(status_sent) FOR Status_sent IN ('
  + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
  + ')
) AS p;';
PRINT @sql;
EXEC sp_executesql @sql;
0
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Copy-paste the below T-SQL into your SSMS, execute it to verify that it works, and modify to meet your needs.
CREATE TABLE mytable (status_sent char(1)) 

INSERT INTO mytable (status_sent) 
VALUES ('B'), ('X'), ('S'), ('N'), ('B')

SELECT 
	COUNT(CASE WHEN status_sent = 'B' THEN 1 END) as Count_B,
	COUNT(CASE WHEN status_sent = 'X' THEN 1 END) as Count_X,
	COUNT(CASE WHEN status_sent = 'S' THEN 1 END) as Count_S,
	COUNT(CASE WHEN status_sent = 'N' THEN 1 END) as Count_N
FROM mytable	
	

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Thanks for the grade.  Good luck with your project.  -Jim
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2005

From novice to tech pro — start learning today.