sqlserver 數據橫向查詢和遊標使用

USE [tempdb]
GO
/****** 對象:  StoredProcedure [dbo].[sp_sum]    腳本日期: 04/26/2013 14:36:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:  <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[sp_sum]
 -- Add the parameters for the stored procedure here

AS
 declare @iii int
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 -- SET NOCOUNT ON
 
    -- Insert statements for procedure here
 --第一步:把數據納入到表tb_jhsy 手工從excle插入到表
 --第二步:把數據插入到表tb_sum
 delete from tb_sum
 declare @result VARCHAR(30)
 Declare curSF Cursor for  
    select distinct xs from tb_jhsy;---查詢語句(查詢所有用戶存儲過程名稱) 
 Open curSF  
  --循環並提取記錄  
  Fetch Next From curSF Into @result--取第一條記錄存入@result中  
  While ( @@Fetch_Status=0 )    
        begin 
   insert into tb_sum(dz,cb,qy,yf,yhyf)
    select @result,b.cb,sum(b.qy),sum(b.yf),sum(b.yfy) from (
    select a.cb,count(a.cb) as qy,0 as yf,0 as yfy from tb_jhsy a
    where a.xs = @result  group by a.cb
    union all
    select a.cb,0 as qy,count(a.cb) as yf,0 as yfy from tb_jhsy a
    where a.xs = @result and a.lb like '全員育婦%' group by a.cb
    union all
    select a.cb,0 as qy,0 as yf,count(a.cb) as yfy from tb_jhsy a
    where a.xs = @result and a.lb like '全員育婦已%' group by a.cb
    ) as b
    group by b.cb
           Fetch Next From curSF into @result ----下一條  
        end  
  --關閉遊標     
   Close curSF 
  --釋放遊標  
 Deallocate curSF  
 --第三步:統計出需要的數據
    declare @s varchar(8000)
 set @s='select cb'
 select @s=@s+',['+ltrim(rtrim(dz))+'qy]=sum(case ltrim(rtrim(dz)) when '''+ltrim(rtrim(dz))+''' then qy else 0 end)'+',['+ltrim(rtrim(dz))+'yf]=sum(case ltrim(rtrim(dz)) when '''+ltrim(rtrim(dz))+''' then yf else 0 end)'+',['+ltrim(rtrim(dz))+'yhyf]=sum(case ltrim(rtrim(dz)) when '''+ltrim(rtrim(dz))+''' then yhyf else 0 end )'
 from tb_sum
 group by dz
 set @s=@s+' from tb_sum group by cb '
 exec(@s)

END

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章