为什么这个SQL Fiddle不起作用?
复制了完整的脚本:
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);
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;
;with cte as (
select id,Number,month,isnull(Value,0.0)value
from @tbl
where Number=1
union all
select cte.id,cte.Number+1,cte.month,isnull(t.value,cte.Value)
from cte
join @tbl t on t.id=cte.id and t.number=cte.number+1
)
/*update t
set value=cte.value
from @tbl t
join cte on t.id=cte.id and t.number=cte.number;*/
select id, Jan,Feb,Mar,Apr,May,Jun
from (select id,month,value from /*@tbl*/ cte) p
pivot (max(value) for month in (Jan,Feb,Mar,Apr,May,Jun)) v;
预期结果:
ID JAN FEB MAR APR MAY JUN
1 0.12 0.36 0.72 0.72 0.72 0.72
2 0 0 0.11 0.12 0.36 0.36
实际结果:
ID JAN FEB MAR APR MAY JUN
1 0.72 (null) (null) (null) (null) (null)
2 0.36 (null) (null) (null) (null) (null)
如果您取消注释已注释掉的代码,它就可以工作。但是,如果您直接从 CTE 中选择,它会显示与UPDATE 语句之后SELECT * FROM CTE
相同的值。@tbl
前段时间我花时间分析CTE + ROW_NUMBER()但希望有人能解释一下。