已知:
表2:
名称  当月产值  上月产值  当月税  上月税    类别
A      10       12        2        3      规上
B      9        5         6        1      规下
C      3        8         4        5      规上
D      13       3         4        6      规上
E      2        3         4        2      规下
得到:
指标名称   规上当月   规上上月  规下当月   规下上月
产值       26        33        11        8
税         10        14        10        3    

解决方案 »

  1.   

    drop table tb
    create table tb
    (
      名称 varchar(10),
      当月产值  int,
      上月产值  int,
      当月税 int,
      上月税 int,
      类别 varchar(10)
    )
    insert into tb
    select 'A',10,12,2,3,'规上' union all
    select 'B',9,5,6,1,'规下' union all
    select 'C',3,8,4,5,'规上' union all
    select 'D',13,3,4,6,'规上' union all
    select 'E',2,3,4,2,'规下'select '产值' as 指标名称
    ,sum(case when 类别='规上' then 当月产值 else 0 end ) as 规上当月
    ,sum(case when 类别='规上' then 上月产值 else 0 end) as 规上上月
    ,sum(case when 类别='规下' then 当月产值 else 0 end) as 规下当月
    ,sum(case when 类别='规下' then 上月产值 else 0 end) as 规下上月
    from tb
    union all
    select '税' as 指标名称
    ,sum(case when 类别='规上' then 当月税 else 0 end ) as 规上当月
    ,sum(case when 类别='规上' then 上月税 else 0 end) as 规上上月
    ,sum(case when 类别='规下' then 当月税 else 0 end) as 规下当月
    ,sum(case when 类别='规下' then 上月税 else 0 end) as 规下上月
    from tb
    ------------------------------
    指标名称 规上当月 规上上月 规下当月 规下上月
    产值 26 23 11 8
    税 10 14 10 3