0

我的查询有一个表格结果,如下所示

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

我想从以下视图的这个表中创建逐年单独的数据透视表

2000 年

    A1    B1     C1
A1        1000   1500
B1 1000
C1 1500

2001 年

    A1    B1     C1
A1        2000   1400
B1 2000
C1 1400

有人可以建议一个查询来自动化结果或可用于获取结果的通用查询。

4

1 回答 1

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
于 2013-07-28T08:27:08.720 回答