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

存储过程中的技术问题
            国家重大项目     国家级项目     部级项目    合计  
项目个数        5               3            1        9
经费(万)      20              10           5        35

我想实现上面的效果,但是我在Projectinfo表中存的是国家重大项目和国家级项目这些级别的编号,
比如类别表中的数据如下
  编号    名称
   1      国家级重大项目
   2      国家级项目
   3      部级项目
则我在Projectinfo表中的ProjectType字段存的是 1 或 2 或 3这些编号。
因为我的编号可能换,所以我必须判断它们的名称分别是什么来计数,
sum(case when ProjectType='2' then 1 else 0 end),这条语句用编号计数可以实现,我该怎么改让他判断级别表中的名称呢?
------最佳解决方案--------------------
我个的结果与楼主要数据结果有肯定有出入,但是你要解决问题的思路已经给出了。(另一个表存主表的ID,查询的时候要根据这个id查询主表数据的name可以直接left join左链接一下就好了)还有一点需要提醒楼主的一个表引用了主表的一个字段那个字段最好就不做修改了。不然这个操作各种麻烦。

--------创建测试数据

--项目类型表
if OBJECT_ID('ItemType_20121129') is not null drop table ItemType_20121129
create table ItemType_20121129(id int identity(1,1),name nvarchar(50))
go
insert into ItemType_20121129(name)
select '国家重大项目' union all
select '国家级项目' union all 
select '部级项目' 

--项目明细表
if OBJECT_ID('Projectinfo_20121129') is not null drop table Projectinfo_20121129
create table Projectinfo_20121129(id int identity(1,1),IT_id int,number int,outlay int)
go
insert into Projectinfo_20121129(IT_id,number,outlay)
select 1,3,9 union all
select 2,5,20 union all 
select 3,4,20 union all
select 2,7,28 union all 
select 3,4,12 union all
select 2,5,15 union all 
select 3,6,24 

--------查询
;with T as(
select IT_id,SUM(number)as [项目个数],SUM(outlay) as [经费(万)] from Projectinfo_20121129 group by IT_id
)
select it.name,t.[项目个数],t.[经费(万)] from T t left join
ItemType_20121129 it on it.id=t.IT_id

--------查询结果
/*
name                                               项目个数        经费(万)
-------------------------------------------------- ----------- -----------
国家重大项目                                             3           9
国家级项目                       &