你可以用PIVOT
这个。如果您有已知数量的列,则可以使用 STATIC PIVOT 对值进行硬编码:
select *
from
(
select substring(name, 1, 1) name, -- use the same field twice,
substring(name, 1, 1) initial -- once will be for the count the other for columns
from yourtable
) x
pivot
(
count(name)
for initial in ([B], [M])
) p
请参阅带有演示的 SQL Fiddle
如果要转换的列数未知,则可以使用动态 sql 并创建动态 PIVOT:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ','
+ QUOTENAME(substring(name, 1, 1))
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + ' from
(
select substring(name, 1, 1) name,
substring(name, 1, 1) initial
from yourtable
) x
pivot
(
count(name)
for initial in (' + @cols + ')
) p '
execute(@query)
请参阅带有演示的 SQL Fiddle
如果您想将数据集过滤为仅以开头的数据集,B or M
则可以使用WHERE
子句进行过滤。
where substring(name, 1, 1) in ('B', 'M')