Transformando Linhas em Colunas no SQL Server

TRANSFORMANDO LINHAS EM COLUNAS NO SQL SERVEr A situação é o seguinte, você tem os dados no banco de dados em uma tabela dispostos da seguinte forma: TRANSFORMANDO LINHAS EM COLUNAS NO SQL SERVEr 1   E deseja que os dados sejam organizados em coluna da seguinte forma: TRANSFORMANDO LINHAS EM COLUNAS NO SQL SERVEr 2   Construindo a tabela de exemplo
create table #teste
(
Id int,
Nome varchar(50),
Categoria varchar(50)
)
Inserindo os dados na tabela de exemplo
insert into #teste
values
(1, 'João', 'A'),
(2, 'João', 'B'),
(3, 'João', 'D'),
(4, 'Maria', 'A'),
(5, 'Maria', 'C'),
(6, 'Maria', 'D')
Verificando os dados
select * from #teste
Transformando linhas em colunas usando case
-- USANDO CASE
select nome,
  max(case when categoria = 'A' then 'X' else '' end) CategoriaA,
  max(case when categoria = 'B' then 'X' else '' end) CategoriaB,
  max(case when categoria = 'C' then 'X' else '' end) CategoriaC,
  max(case when categoria = 'D' then 'X' else '' end) CategoriaD
from #teste
group by nome
Transformando linhas em colunas usando Join
-- USANDO JOINS
select c1.nome,
  case when c1.Categoria is not null then 'X' else '' end as CategoriaA,
  case when c2.Categoria is not null then 'X' else '' end as CategoriaB,
  case when c3.Categoria is not null then 'X' else '' end as CategoriaC,
  case when c4.Categoria is not null then 'X' else '' end as CategoriaD
from #teste c1
left join #teste c2
  on c1.nome = c2.nome
  and c2.Categoria = 'B'
left join #teste c3
  on c1.nome = c3.nome
  and c3.Categoria = 'C'
left join #teste c4
  on c1.nome = c4.nome
  and c4.Categoria = 'D'
where c1.Categoria = 'A'
Transformando linhas em colunas usando Pivot
-- USANDO PIVOT
select nome,
  coalesce(A, '') CategoriaA,
  coalesce(B, '') CategoriaB,
  coalesce(C, '') CategoriaC,
  coalesce(C, '') CategoriaD
from
(
  select nome, Categoria, 'X' flag
  from #teste
) d
pivot
(
  max(flag)
  for Categoria in (A, B, C, D)
) piv
Transformando linhas em colunas usando Pivot Dinâmico
-- USANDO PIVOT DINAMICO
DECLARE @cols AS NVARCHAR(MAX),
    @colsNull AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(Categoria)
from #teste
group by Categoria
order by Categoria
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')

select @colsNull = STUFF((SELECT ', coalesce(' + QUOTENAME(Categoria)+', '''') as '+QUOTENAME('Categoria'+Categoria)
from #teste
group by Categoria
order by Categoria
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')

set @query = 'SELECT nome, ' + @colsNull + '
from
(
select nome, Categoria, ''X'' flag
from #teste
) x
pivot
(
max(flag)
for Categoria in (' + @cols + ')
) p '

execute(@query)

Loading