The table looks like below.
DROP TABLE #TEMP CREATE TABLE #TEMP ( UVRID VARCHAR(20), DynamoNo INT, FREQHZ INT ) INSERT #TEMP SELECT '15AL78',100,10 UNION ALL SELECT '15AL78',110,20 UNION ALL SELECT '257T13',100,10 UNION ALL SELECT '257T13',110,20 UNION ALL SELECT '257T13',931,30
I am trying to make 1 new column say SuprerFrez
whose value is depends on column FREQHZ
.
For every UVRID
group 2nd value FREQHZ
will be 1st value of SuprerFrez
and for last FREQHZ
, SuprerFrez
value will be zero.
Expected output with 1 new column whose value depends upon FREQHZ
column. Order by FREQHZ ASC
UVRID |DynamoNo|FREQHZ|SuprerFrez '15AL78'|100 |10 |20 '15AL78'|110 |20 |0 '257T13'|100 |10 |20 '257T13'|110 |20 |30 '257T13'|931 |30 |0
Advertisement
Answer
You are looking for lead()
:
select t.*, lead(FREQhz, 1, 0) over (partition by UVRID order by DynamoNo) as SuprerFrez from #temp t;
Note this assumes that the ordering is by DynamoNo
. If that is not the ordering you have in mind, then you need another column that specifies the ordering. For instance, if you wanted “insert” order, you could use an identity
column:
CREATE TABLE #TEMP ( TempID INT IDENTITY(1, 1) PRIMARY KEY, UVRID VARCHAR(20), DynamoNo INT, FREQHZ INT );
Then the code would look like:
select t.*, lead(FREQhz, 1, 0) over (partition by UVRID order by TempID) as SuprerFrez from #temp t;