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 に答える