You can use PIVOT for this. If you have a known number of columns, you can adjust the values ββusing STATIC PIVOT:
select * from ( select substring(name, 1, 1) name,
See SQL Fiddle With Demo
If you have an unknown number of columns to convert, you can use dynamic sql and create a dynamic 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)
See SQL script for a demo
If you want to filter the dataset only for those that start with B or M , you can use the WHERE to filter.
where substring(name, 1, 1) in ('B', 'M')
source share