I\'m needing some help. I have two columns, Place and Name, I want a count of Name for each place. Currently the data would look like:
Place | Name
100 OK
10
Your current query is close but since you want to count
the number of names
you can just use that as the aggregate function, instead of using the CASE
statement in your subquery and then averaging.
My suggestion would always be to write the query as a static version first before trying to write a dynamic SQL server, mainly to get the syntax correct:
select place, Bad, New, OK
from
(
select place, name
from info_table
) d
pivot
(
count(name)
for name in (Bad, New, OK)
) p;
See SQL Fiddle with Demo. Once you have the logic correct, then you can easily turn this to dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
SELECT @cols = STUFF((SELECT distinct
',' +
QUOTENAME(NAME)
FROM INFO_TABLE with (nolock)
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
SET @query = ' SELECT PLACE , ' + @cols + '
FROM
(
SELECT NAME, PLACE
FROM INFO_TABLE with (nolock)
) t
PIVOT
(
count(name)
FOR NAME IN (' + @cols + ' )
)
p ' ;
Execute(@query);
See SQL Fiddle with Demo