将一个字段的多个记录值合在一行

a b c
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

 

posted @ 2011-05-05 14:49  Shikyoh  阅读(324)  评论(0编辑  收藏  举报