你真的需要使用跨產品製造缺失的記錄,以便左連接,使他們出現
declare @table table
(
n int not null,
ch char(1) not null,
cnt int not null,
primary key (n, ch)
)
insert into @table values (5, 'A', 12)
insert into @table values (5, 'B', 81)
insert into @table values (5, 'C', 107)
insert into @table values (3, 'A', 1)
insert into @table values (3, 'B', 12)
insert into @table values (3, 'C', 12)
insert into @table values (3, 'D', 5)
insert into @table values (2, 'A', 3)
declare @numbers table (n int not null primary key)
insert into @numbers values (1)
insert into @numbers values (2)
insert into @numbers values (3)
insert into @numbers values (4)
insert into @numbers values (5)
declare @chars table (ch char(1) not null primary key)
insert into @chars values ('A')
insert into @chars values ('B')
insert into @chars values ('C')
insert into @chars values ('D')
select n, [A], [B], [C], [D]
from
(-- manufacture missing records
select n.n, ch.ch, coalesce(t.cnt, 0) as cnt
from @numbers n
cross join @chars ch
left join @table t on (n.n = t.n and ch.ch = t.ch)
) as t
pivot
(
sum(cnt)
for ch in ([A], [B], [C], [D])
) as pivotTable
order by n desc
請出示你的源數據和當前'pivot'語句看起來象。 –