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

sqlserver整合数据问题,按年排序问题
本帖最后由 zy021120621 于 2013-05-17 15:03:48 编辑
现在有2个表,xxb里面是企业名称和企业代码,是所有公司的信息表。
表2是xsjl是我们管理企业的09,10,11年,3年的按月录入的销售额的表里面只有企业名称,企业的销售月份,企业的销售额


我想生成个表3 或者直接查询显示也行  表3的内容包括企业的代码   企业的名称   企业09年度销售额  企业10年度销售额   企业11年度销售额

其中我能做出整合某一年的工作,
即我先从XXB中找出企业代码,然后将日期在一年内的数据找到,求和,显示,



但是无法实现其他2年数据的加和,求高手解答

SQL?Server 行业数据 企业

------解决方案--------------------
if OBJECT_ID('baseInfo') is not null  
drop table baseInfo
go

create table baseInfo
(
code int identity(1,1),
name varchar(20)
)

if OBJECT_ID('xsjl') is not null  
drop table baseInfo
go
create table xsjl
(
name varchar(20),
mdate date,
sales decimal(12,2)
)

insert into baseInfo(name)
select 'comp1' union all
select 'comp2'

insert into xsjl
select 'comp1','2009-1-5',10 union all
select 'comp1','2009-5-5',10 union all
select 'comp1','2010-1-5',30 union all
select 'comp1','2010-5-5',30 union all
select 'comp1','2011-1-5',50 union all
select 'comp1','2011-5-5',50 union all
select 'comp2','2009-1-5',50 union all
select 'comp2','2011-5-5',50
go

select 
t.name,
sum(case YEAR(t1.mdate) when 2009 then sales else 0 end)'企业09年度销售额', 
sum(case YEAR(t1.mdate) when 2010 then sales else 0 end) '企业09年度销售额',
sum(case YEAR(t1.mdate) when 2011 then sales else 0 end) '企业09年度销售额'
from
baseInfo t
inner join xsjl t1 on t.name=t1.name
group by t.name