isnull pivot server sql_SQL Server Pivot用最后一列替换null

Pivot table:

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

Result:

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

At the begin of the cell in row/column if there is no value null should be replaced by 0 and then previous cell in the row should fill the next cell in the same row if there is null.

解决方案-- 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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值