我有一个具有以下结构的表:
Name Code
---- ---
Jonh A01
Jonh A02
Jonh A01
Jonh A02
Jonh A03
我需要这个:
Name A01 A02 A03
---- --- --- ---
Jonh 2 2 1
你能帮帮我吗?
答案 0 :(得分:0)
您需要一个透视查询,请试一试:
declare @t as table (Name varchar(50), Code varchar(50));
insert @t (Name, Code)
values
('Jonh', 'A01')
,('Jonh', 'A02')
,('Jonh', 'A01')
,('Jonh', 'A02')
,('Jonh', 'A03');
select Name
,A01
,A02
,A03
from (
select Name
,Code
from @t
) up
PIVOT(COUNT(Code) for Code in (
A01
,A02
,A03
)) as pvt;