尝试这个。这有点简单但有效:)
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