Avatar of VBdotnet2005
VBdotnet2005Flag for United States of America asked on

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
Microsoft SQL Server 2005Microsoft SQL Server 2008

Avatar of undefined
Last Comment
Jim Horn

8/22/2022 - Mon
x-men

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;
ASKER CERTIFIED SOLUTION
Jim Horn

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Jim Horn

Thanks for the grade.  Good luck with your project.  -Jim
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck