日期:2014-05-17  浏览次数:20617 次

求助 sql 语句?
我想得到这样的表格:
单位名称         月份1  月份2  月份3。。。。。月份12
单位一    计划   10     20    30
          实际   20     30    40
          盈亏   10     10    10
单位二    计划   10     20    30
        实际   20     30    40
        盈亏   10     10    10


数据库中能得到下面的数据:


单位名称  月份  计划  实际  盈亏
单位一    1    10   20   10


单位是动态的。

------解决方案--------------------
select 单位名称 月份=1,其它列... from 表 
union all
select 单位名称 月份=2,其它列... from 表 
uinon all...
------解决方案--------------------

create table tb 
(
单位名称 nvarchar(10),
col nvarchar(10),
月份1 int,
月份2 int,
月份3 int
)
insert into tb values('单位一','计划',10,20,30)
insert into tb values('单位一','实际',20,30,40)
insert into tb values('单位一','盈亏',10,10,10)
insert into tb values('单位二','计划',10,20,30)
insert into tb values('单位二','实际',20,30,40)
insert into tb values('单位二','盈亏',10,10,10)



select 单位名称,1,max(case when col = '计划' then 月份1 end) 计划,
max(case when col = '实际' then 月份1 end) 实际,
max(case when col = '盈亏' then 月份1 end) 盈亏
from tb 
group by 单位名称
union all
select 单位名称,2,max(case when col = '计划' then 月份2 end) 计划,
max(case when col = '实际' then 月份2 end) 实际,
max(case when col = '盈亏' then 月份2 end) 盈亏
from tb 
group by 单位名称
unall all ...
/*
单位名称,,计划,实际,盈亏
单位二,1,10,20,10
单位一,1,10,20,10
单位二,2,20,30,10
单位一,2,20,30,10
警告: 聚合或其他 SET 操作消除了空值。

(4 行受影响)