a b c
a b c1
a b c2
a b c3
a b c1
a b c2
a b c3
--定义函数
create function getstr(@id nvarchar(50))
returns Nvarchar(4000)
as
begin
declare @str Nvarchar(2000)
-- 给 @str赋值
set @str=N''
select @str=@str+rtrim(c)+N',' from temp
where a=@id
--判断是否为空
if @str <> N''
set @str=left(@str,len(@str)-1)
return @str
end
GO
--调用 函数
select a,dbo.getstr(a) from temp group by a
其他方法:
--使用Pivot select cycleName,sum(a),sum(b),sum(c),sum(d) from (select * from [SM_MonitorEvent] pivot ( count(eventType) for eventType in (a,b,c,d) )tab ) a group by cycleName --使用sum select cycleName, sum(case EventType when 'a' then 1 else 0 end) a, sum(case EventType when 'b' then 1 else 0 end) b, sum(case EventType when 'c' then 1 else 0 end) c, sum(case EventType when 'd' then 1 else 0 end) d from [SM_MonitorEvent] group by cycleName