SQL Server Make custom column using variables and conditions off another column

ykejflvf  于 2023-05-05  发布在  其他
关注(0)|答案(1)|浏览(121)

I have a simple query that pulls data from multiple tables with a few conditions

select x, step, code, ....,
from 
table 1
inner join table 2
inner join table 3
where
'filters'
order by x, code

This gives me a table where two columns with step and code:

xstepcode
100001
1100000
1200000
1300000
1400000
110000001
200000
2100000
2200000

As above, the 0 step indicates whether the process failed and the sub-step shows exactly which part. Then when step goes back to 0 it is now a new process.

Is there a way to pull the 0 step value of the code (so in this case it would be "0001") and then use that value as the code until it reaches the next step 0 and update the value?

So the table would now look like this:
| x | step | code |
| ------------ | ------------ | ------------ |
| 1 | 0 | 0001 |
| 1 | 10 | 0001 |
| 1 | 20 | 0001 |
| 1 | 30 | 0001 |
| 1 | 40 | 0001 |
| 1 | 1000 | 0001 |
| 2 | 0 | 0000 |
| 2 | 10 | 0000 |
| 2 | 20 | 0000 |

It can be a new column, I just indicated the same one to save time.

Any help is appreciated, thanks

vltsax25

vltsax251#

You confused code with step in your ORDER BY clause. Change this, so as to get a deterministic result with step 0 always being the first step shown for an x.

Use FIRST_VALUE to get the code for step 0 per x.

select x, step, first_value(code) over (partition by x order by step) as xcode
inner join table 2
inner join table 3
where <filters>
order by x, step;

相关问题