繁体   English   中英

SQL 服务器 - Select 下一行值最多 5 个字符,然后用新字符替换第一个字符

[英]SQL SERVER - Select next row value upto 5 characters and then replace first character with new one

我有一种情况,我想读取同一列的下一个值并将其连接最多五个字符并将其存储在不同的列中,但我无法这样做请参阅下文以获得更好的可视化效果。

这是输入

------------------------------
|      ID      |   word      |
------------------------------
|       1      |      M      |
|       2      |      V      |
|       3      |      V      |
|       4      |      M      |
|       5      |      V      |
|       6      |      M      |
|       7      |      V      |
|       8      |      M      |
|       9      |      V      |
|       10     |      V      |
------------------------------

所需的 output:

-------------------------------------------- 
|      ID      |   word      |  expected   |
--------------------------------------------
|       1      |      M      |      M      |
|       2      |      V      |      MV     |
|       3      |      V      |      MVV    |
|       4      |      M      |      MVVM   |
|       5      |      V      |      MVVMV  |
|       6      |      M      |      VVMVM  |
|       7      |      V      |      VMVMV  |
|       8      |      M      |      MVMVM  |
|       9      |      V      |      VMVMV  |
|       10     |      V      |      MVMVV  |
--------------------------------------------

在此预期列中,当它到达第 6 行并尝试 append 时附加第 5 个字符后,它将首先从“MVVMV”(第 5 行)中删除第一个字符“M”,然后从第 6 行末尾的 append“M”中删除“M” 'MVVMV' 将是 'VVMVM'

我希望你能理解这个逻辑,因为我已经尝试了很多方法来实现这个但没有运气

谢谢

您可以使用lag()concat()

select t.*,
       concat(lag(word, 4) over (order by id),
              lag(word, 3) over (order by id),
              lag(word, 2) over (order by id),
              lag(word, 1) over (order by id),
              word
             ) as concat_5
from t;

不幸的是,SQL 服务器(还)不支持STRING_AGG()作为 window function。如果支持,您可以使用:

select t.*,
       string_agg(word) within group (order by id) over
            (order by id rows between 4 preceding and current row) as concat_5
from t;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM