2013-07-27 81 views
0

我從我的查詢表中的結果是如下透視表視圖2005

company1 company2 year revenue 
--------------------------------- 
A1  B1  2000 1000 
B1  A1  2001 2000 
A1  C1  2000 1500 
C1  A1  2001 1400 

我想從該表中以下視圖的創建yearwise單獨的數據透視表

對於2000

A1 B1  C1 
A1  1000 1500 
B1 1000 
C1 1500 

對於2001年

A1 B1  C1 
A1  2000 1400 
B1 2000 
C1 1400 

有人可以建議一個查詢來自動化結果或可用於獲得結果的通用查詢。

回答

0

試試這個。這是簡單的一點點,但工作:)

create table my_query (
    company1 nvarchar(100), 
    company2 nvarchar(100), 
    [year] int, 
    revenue int, 
); 

insert into my_query (company1, company2, [year], revenue) values ('A1', 'B1', 2000, 1000); 
insert into my_query (company1, company2, [year], revenue) values ('B1', 'A1', 2001, 2000); 
insert into my_query (company1, company2, [year], revenue) values ('A1', 'C1', 2000, 1500); 
insert into my_query (company1, company2, [year], revenue) values ('C1', 'A1', 2001, 1400); 

---------------------------------------------------------------- 
create procedure yearwise 
    @year int 
as 
begin 
    declare @code nvarchar(max); 
    set @code = ''; 

    select @code = @code + [code] from (
     select 'select src.company' [code], 1 [sort] 
     union 
     select ', (select sum(revenue) [sum] from my_query where [year] = '+cast(@year as nvarchar)+' and ((company1 = src.company and company2 = '''+company1+''') or (company1 = '''+company1+''' and company2 = src.company))) ['+company1+']', 2 from my_query 
     union 
     select 'from (select company1 [company] from my_query union select company2 from my_query) as src', 3 
    ) as tbl 
    order by [sort] 

    exec (@code); 
end 
---------------------------------------------------------------- 

exec yearwise @year = 2001 

結果

company A1  B1  C1 
---------------------------- 
A1  NULL 2000 1400 
B1  2000 NULL NULL 
C1  1400 NULL NULL