Tricky Query:
Query to convert source table result table
Logic: where ever salary is 0 the salary value changed to previous non zero salary
Source table:
name | sal |
a | 0 |
a | 10 |
a | 20 |
a | 0 |
a | 30 |
a | 0 |
a | 0 |
a | 40 |
a | 0 |
Result Table:
row_id | name | sal | ene |
1 | a | 0 | 0 |
2 | a | 10 | 10 |
3 | a | 20 | 20 |
4 | a | 0 | 20 |
5 | a | 30 | 30 |
6 | a | 0 | 30 |
7 | a | 0 | 30 |
8 | a | 40 | 40 |
9 | a | 0 | 40 |
Create table #abc(name varchar(10),sal int)
insert into #abc select 'a', 0
insert into #abc select 'a', 10
insert into #abc select 'a', 20
insert into #abc select 'a', 0
insert into #abc select 'a', 30
insert into #abc select 'a', 0
insert into #abc select 'a', 0
insert into #abc select 'a', 40
insert into #abc select 'a', 0
select * from #abc
with cte
as
(select name,sal ,Row_number() over (order by (select 0)) as row_id from #abc)
select v.row_id,v.name,v.sal ,case v.sal when 0 then isnull((select top 1 a.sal from cte a where a.row_id<v.row_id and a.sal <>0 order by row_id desc),0) else v.sal end as ene from cte v
No comments:
Post a Comment