日期:2014-05-18 浏览次数:20493 次
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[YearPlan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[YearPlan] GO CREATE TABLE [dbo].[YearPlan] ( [Id] [int] NOT NULL , [Org_Id] [int] NOT NULL , [Category_Id] [int] NOT NULL , [Years] [int] NULL , [Moth] [int] NULL , [Plans] [decimal](18, 0) NULL , [Complete] [decimal](18, 0) NULL , [CompleteRatio] [nvarchar] (8) COLLATE Chinese_PRC_CI_AS NULL , [SubmitTime] [datetime] NULL , [Status] [char] (4) COLLATE Chinese_PRC_CI_AS NULL , [Operator_Id] [nvarchar] (16) COLLATE Chinese_PRC_CI_AS NOT NULL ) ON [PRIMARY] GO
--建立测试环境 set nocount on create table test(ID varchar(20),年 int,月 int,计划 int,完成 int,完成率 float) insert into test select '1','2008','3','100','80','80' insert into test select '2','2008','1','100','3','3' go --测试 select 年,'计划', sum(case when 月=1 then 计划 else 0 end )[1月], sum(case when 月=2 then 计划 else 0 end )[2月], sum(case when 月=3 then 计划 else 0 end )[3月], --... sum(case when 月=12 then 计划 else 0 end )[12月] from test group by 年 union select 年,'完成', sum(case when 月=1 then 完成 else 0 end )[1月], sum(case when 月=2 then 完成 else 0 end )[2月], sum(case when 月=3 then 完成 else 0 end )[3月], --... sum(case when 月=12 then 完成 else 0 end )[12月] from test group by 年 union select 年,'完成率', sum(case when 月=1 then 完成率 else 0 end )[1月], sum(case when 月=2 then 完成率 else 0 end )[2月], sum(case when 月=3 then 完成率 else 0 end )[3月], --... sum(case when 月=12 then 完成率 else 0 end )[12月] from test group by 年 --删除测试环境 drop table test set nocount off
------解决方案--------------------
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[YearPlan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[YearPlan]
GO
CREATE TABLE YearPlan (
[Id] [int] NOT NULL identity(1,1),
[Years] [int] NULL ,
[Moth] [int] NULL ,
[Plans] [decimal](18, 0) NULL ,
[Complete] [decimal](18, 0) NULL ,
[CompleteRatio] [nvarchar] (8) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
insert into YearPlan
select 2007,1,100,80,'80' union all
select 2007,1,200,80,'40' union all
select 2007,2,200,80,'40' union all
select 2007,2,80,80,'100' union all
select 2007,3,200,80,'40' union all
select 2007,4,800,80,'10' union all
select 2007,5,400,80,'20' union all
select 2007,6,400,80,'20' union all
select 2007,7,400,80,'20' union all
select 2007,8,400,80,'20' union all
select 2007,8,200,80,'40' union all
select 2007,9,200,80,'40' union all
select 2007,10,200,80,'40' union all
select 2007,11,200,80,'40' union all
select 2007,12,200,80,'40' union all
select 2008,1,100,80,'80' union all