2012-10-03 18 views
0

透视表:SQL Server的支点与最后一列替换空

id Jan Feb March April May June 
========================================= 
1 0.12 0.36 0.72 null null null 
2 null null 0.11 0.12 0.36 null 

结果:

id Jan Feb March April May June 
========================================= 
1 0.12 0.36 0.72 0.72 0.72 0.72  
2 0.00 0.00 0.11 0.12 0.36 0.36 

在开始行/列的单元格,如果没有null值应代之以0,那么行中的前一个单元格应该填充同一行中的下一个单元格(如果为null)。

+0

欢迎来到Stack Overflow!请注意,标签独立。谈论单一事物时,不能合并多个标签。也就是说,用'sql'和'server'标记你的问题并不意味着你在谈论Microsoft SQL Server。 – Charles

+0

请发布您当前的查询。这可能是因为内部连接或某些其他不提供结果= 0的排除方法。 –

回答

1
-- sample table for discussion 
create table tbl (
    id int, 
    month varchar(9), 
    value float); 
insert tbl values 
(1,'Jan',0.12), 
(1,'Feb',0.36), 
(1,'Mar',0.72), 
(2,'Mar',0.11), 
(2,'Apr',0.12), 
(2,'May',0.36); 

-- beginning of script 
declare @tbl table (
    id int, 
    number int, 
    month varchar(9), 
    value float); 
insert @tbl 
select id.id, Months.Number, Months.Name, t.value 
from (values(1,'Jan'), 
      (2,'Feb'), 
      (3,'Mar'), 
      (4,'Apr'), 
      (5,'May'), 
      (6,'Jun')) Months(Number,Name) 
cross join (select distinct id from tbl) id 
left join tbl t on t.month = Months.name and t.id=id.id; 

-- fully populate the table with all id/month combinations filled in 
;with cte as (
    select id,Number,month,isnull(Value,0.0)value 
    from @tbl 
    where Number=1 
    union all 
    select cte.id,t.Number,t.month,isnull(t.value,cte.Value) 
    from cte 
    join @tbl t on t.id=cte.id and t.number=cte.number+1 
) 
-- this is what the original pivot would have looked like 
select id, Jan,Feb,Mar,Apr,May,Jun 
from (select id,month,value from cte) p 
pivot (max(value) for month in (Jan,Feb,Mar,Apr,May,Jun)) v;