Link to home
Start Free TrialLog in
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
Avatar of x-men
x-men
Flag of Portugal image

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
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the grade.  Good luck with your project.  -Jim