2011-11-22 54 views
2

有沒有使用Pivot包含沒有記錄的行並顯示0或結果爲空的行的方法?顯示SQL Pivot的所有行,包括那些記錄計數爲零的行

我想查詢的reults看起來是這樣的: -

 A B C D 
5 12 81 107 0 
4 0  0 0 0 
3 1 12 12 5 
2 3 0  0 0 
1 0 0  0 0 

然而,目前樞軸沒有返回空行和我的結果是這樣的: -

 A B C D 
5 12 81 107 0 
3 1 12 12 5 
2 3 0  0 0 

任何這種方式可以通過在Pivot上進行某種「左外連接」來顯示所有行來實現?

+2

請出示你的源數據和當前'pivot'語句看起來象。 –

回答

2

你真的需要使用跨產品製造缺失的記錄,以便左連接,使他們出現

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 
相關問題