您可以使用PIVOT
這一點。如果你有一個著名的列數,那麼你可以硬編碼一個靜態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 With Demo
如果你有數目不詳的轉變列的,那麼你可以使用動態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 with Demo
然後,如果您要過濾的數據集下來鄰只有那些以B or M
開頭的條目纔可以使用WHERE
條款進行過濾。
where substring(name, 1, 1) in ('B', 'M')
我不知道工會是如何讓你的兩列 – Paparazzi