Create  table #corpinfo
(
  [corp_id] varchar(10),
  [Corp_Create_Time] datetime,
  [DISTRICT_TYPE_ID] varchar(3)
)
insert #corpinfo
select 'A','2005-01-01','001' union
select 'B','2005-01-01','001' union
select 'C','2005-03-01','001' union
select 'D','2005-04-01','002' union
select 'E','2005-05-01','002' union
select 'F','2005-06-01','003' union
select 'G','2005-07-01','004' union
select 'H','2005-08-01','005' union
select 'I','2005-09-01','005' 
select corp_id,Convert(Varchar(7),Corp_Create_Time,120) ymonth,DISTRICT_TYPE_ID into #test from #corpinfo --加上你的条件,和你的区域信息
--动态SQL
declare @s varchar(8000)
set @s='select [ymonth] '
select @s=@s+',['+[DISTRICT_TYPE_ID]+']=case when [DISTRICT_TYPE_ID]='''+[DISTRICT_TYPE_ID]+''' then count(*)else 0 end'
from #test 
group by [DISTRICT_TYPE_ID]set @s=@s+',合计=count(*)  from #test group by [ymonth] , DISTRICT_TYPE_ID  'exec(@s)
drop table #corpinfo
drop table #test

解决方案 »

  1.   

    create table corpinfo( 
      corp_id  varchar(10),
      Corp_Create_Time datetime,
      DISTRICT_TYPE_ID varchar(3) 
    )
    insert corpinfo
    select 'A','2005-01-01','001' union
    select 'B','2005-01-01','001' union
    select 'C','2005-03-01','001' union
    select 'D','2005-04-01','002' union
    select 'E','2005-05-01','002' union
    select 'F','2005-06-01','003' union
    select 'G','2005-07-01','004' union
    select 'H','2005-08-01','003' union
    select 'I','2005-09-01','003' --区域代码表  
    create table district(
      code varchar(3),   
      memo varchar(64) 
    )
    insert into district
    select '001','区域1' union all
    select '002','区域2' union all
    select '003','区域3' union all
    select '004','区域4'
    GO
    declare  @s1 varchar(8000),@s2 varchar(8000),@s3 varchar(8000)
    select @s1='',@s2='',@s3=''
    set @s1='select 月份=replace(convert(char(7),a.Corp_Create_Time,126),''-'',''年'')+''月'''
    select @s2=@s2+',['+memo+']=sum(case b.memo when '''+memo+''' then 1 else 0 end)' from district
    set @s1=@s1+@s2+',小计=count(a.corp_id) from corpinfo a,district b 
    where a.DISTRICT_TYPE_ID=b.code group by replace(convert(char(7),a.Corp_Create_Time,126),''-'',''年'')+''月'''
    set @s3=' union all select ''合计'''+@s2+
    ',小计=count(a.corp_id) from corpinfo a,district b where a.DISTRICT_TYPE_ID=b.code'
    exec(@s1+@s3)
    /*
    月份 区域1 区域2 区域3 区域4 小计
    ---------------------------------------------------------
    2005年01月 2 0 0 0 2
    2005年03月 1 0 0 0 1
    2005年04月 0 1 0 0 1
    2005年05月 0 1 0 0 1
    2005年06月 0 0 1 0 1
    2005年07月 0 0 0 1 1
    2005年08月 0 0 1 0 1
    2005年09月 0 0 1 0 1
    合计 3 2 3 1 9*/DROP TABLE corpinfo ,district