日期:2014-05-18  浏览次数:20430 次

求一条语句,今天脑壳失灵了
CREATE TABLE Test(序号 smallint,年份 char(4),产品名称 char(10),销售公司 char (8),销售计划 smallint)
GO
insert into test select  
1,'2011 ','甲产品','北京公司',100 union all select  
2,'2011 ','乙产品','北京公司',200 union all select  
3,'2011 ','甲产品','上海公司',150 union all select  
4,'2011 ','乙产品','上海公司',250 union all select  
5,'2011 ','甲产品','广州公司',300 union all select  
6,'2011 ','乙产品','广州公司',350 

想得到的结果是:
序号 年份 产品名称 北京公司计划 上海公司计划 广州公司计划  
1 2011 甲产品 100 150 300  
2 2011 乙产品 200 250 350 

我感觉用自连接就很容易得到,可是还有点问题,请高手指点,看来休息不好脑壳就是不好使了,O(∩_∩)O~

------解决方案--------------------
SQL code
行列转换

select
   年份,产品名称,
   max(case 销售公司 when '北京公司' then 销售计划 else 0 end) as '北京公司计划',
   max(case 销售公司 when '上海公司' then 销售计划 else 0 end) as '上海公司计划',
   max(case 销售公司 when '广州公司' then 销售计划 else 0 end) as '广州公司计划'
from
   tset
group  by
      年份,产品名称,

------解决方案--------------------
SQL code
if object_id('Test') is not null drop table Test;
go

CREATE TABLE Test(序号 smallint,年份 char(4),产品名称 char(10),销售公司 char (8),销售计划 smallint)
GO
insert into test select  
1,'2011 ','甲产品','北京公司',100 union all select  
2,'2011 ','乙产品','北京公司',200 union all select  
3,'2011 ','甲产品','上海公司',150 union all select  
4,'2011 ','乙产品','上海公司',250 union all select  
5,'2011 ','甲产品','广州公司',300 union all select  
6,'2011 ','乙产品','广州公司',350
go

select Row_Number() over(order by getdate()) as 序号, *
from (select distinct 年份,产品名称,销售公司,销售计划 from Test) x
pivot
(max(销售计划) for 销售公司 in (北京公司,上海公司,广州公司))a

------解决方案--------------------
SQL code

select a.序号,a.年份,a.产品名称,a.销售计划 as 北京公司计划 ,b.销售计划 as 上海公司计划,c.销售计划 as  广州公司计划 
from test as a,test as b,test as c
where a.产品名称=b.产品名称 and b.产品名称=c.产品名称
and a.销售公司='北京公司' and b.销售公司='上海公司' and c.销售公司='广州公司'

------解决方案--------------------
SQL code


--2000
select
   序号=(select count(distinct 产品名称) from Test where 产品名称<=t.产品名称),
   年份,产品名称,
   max(case 销售公司 when '北京公司' then 销售计划 else 0 end) as '北京公司计划',
   max(case 销售公司 when '上海公司' then 销售计划 else 0 end) as '上海公司计划',
   max(case 销售公司 when '广州公司' then 销售计划 else 0 end) as '广州公司计划'
from
   Test t
group  by
   年份,产品名称