sql server 行变成列的DEMO

create table A
(
 属性ID int,
 年份 int
)

delete a
select * From  A

insert  A
select 1, 2008
insert  A
select 2, 2009

create table B
(
 年份 int,
 月份 int,
    金额 int

)
insert B
select 2008,1,20
insert B
select 2008,2,30
insert B
select 2008,3,40
insert B
select 2008,4,10
insert B
select 2009,1,60
insert B
select 2009,2,25
insert B
select 2009,3,5
insert B
select 2009,4,10


select
  A.属性ID,
  A.年份,
   max(case when (A.年份=B.年份) and (B.月份=1) then B.金额 END) as '一月',
 max(case when (A.年份=B.年份) and (B.月份=2) then B.金额 END) as '二月',
 max(case when (A.年份=B.年份) and (B.月份=3) then B.金额 END) as '三月',
 max(case when (A.年份=B.年份) and (B.月份=4) then B.金额 END) as '四月'
From A
  inner join B on A.年份 = B.年份
group by A.属性ID,A.年份

 

 

 

1 2008 20 30 40 10
2 2009 60 NULL 5 10

posted @ 2009-11-02 18:13  CODE  阅读(312)  评论(0编辑  收藏  举报