Ada beberapa cara untuk mengubah data. Beberapa menggunakan fungsi agregat dan yang lainnya tidak. Tetapi meskipun Anda memutar string, Anda masih dapat menerapkan agregat.
Menggabungkan dengan KASUS:
select name,
max(case when category = 'A' then 'X' else '' end) CategoryA,
max(case when category = 'B' then 'X' else '' end) CategoryB,
max(case when category = 'C' then 'X' else '' end) CategoryC,
max(case when category = 'D' then 'X' else '' end) CategoryD
from yourtable
group by name
Lihat SQL Fiddle dengan Demo
Pivot Statis:
Anda masih dapat menggunakan PIVOT
berfungsi untuk mengubah data meskipun nilainya berupa string. Jika Anda memiliki jumlah kategori yang diketahui, maka Anda dapat membuat hard-code kueri:
select name,
coalesce(A, '') CategoryA,
coalesce(B, '') CategoryB,
coalesce(C, '') CategoryC,
coalesce(C, '') CategoryD
from
(
select name, category, 'X' flag
from yourtable
) d
pivot
(
max(flag)
for category in (A, B, C, D)
) piv
Lihat SQL Fiddle dengan Demo .
Pivot Dinamis:
Jika Anda memiliki jumlah kategori yang tidak diketahui, Anda dapat menggunakan SQL dinamis:
DECLARE @cols AS NVARCHAR(MAX),
@colsNull AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(category)
from yourtable
group by category
order by category
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsNull = STUFF((SELECT ', coalesce(' + QUOTENAME(category)+', '''') as '+QUOTENAME('Category'+category)
from yourtable
group by category
order by category
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT name, ' + @colsNull + '
from
(
select name, category, ''X'' flag
from yourtable
) x
pivot
(
max(flag)
for category in (' + @cols + ')
) p '
execute(@query)
Lihat SQL Fiddle dengan Demo .
Beberapa Gabung:
select c1.name,
case when c1.category is not null then 'X' else '' end as CategoryA,
case when c2.category is not null then 'X' else '' end as CategoryB,
case when c3.category is not null then 'X' else '' end as CategoryC,
case when c4.category is not null then 'X' else '' end as CategoryD
from yourtable c1
left join yourtable c2
on c1.name = c2.name
and c2.category = 'B'
left join yourtable c3
on c1.name = c3.name
and c3.category = 'C'
left join yourtable c4
on c1.name = c4.name
and c4.category = 'D'
where c1.category = 'A'
Lihat SQL Fiddle dengan Demo
Semua pertanyaan akan memberikan hasil:
| NAME | CATEGORYA | CATEGORYB | CATEGORYC | CATEGORYD |
--------------------------------------------------------
| Joe | X | X | | X |
| Mary | X | | X | X |