[英]Value from 2nd Row of column copied to 1st row of next column
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
.我正在尝试制作 1 个新列
SuprerFrez
,其值取决于列FREQHZ
。
For every UVRID
group 2nd value FREQHZ
will be 1st value of SuprerFrez
and for last FREQHZ
, SuprerFrez
value will be zero.对于每个
UVRID
组,第二个值FREQHZ
将是SuprerFrez
的第一个值,对于最后一个FREQHZ
, SuprerFrez
值将为零。
Expected output with 1 new column whose value depends upon FREQHZ
column.预期 output 具有 1 个新列,其值取决于
FREQHZ
列。 Order by FREQHZ ASC
通过
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
You are looking for lead()
:您正在寻找
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
.请注意,这假设按
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:例如,如果您想要“插入”订单,您可以使用
identity
列:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.