根据与 SQL 中其他 table 的巧合,从同一字段连接行?
Concat rows from the same field, according to coincidence with other table in SQL?
我在尝试从 table t1
上传字段 caracter
时遇到问题。如果它出现在 t2
的 frase
中,我想将 caracter
的值与之前的值连接起来。例如,如果在 caracter
中找到 x、y 或 z,并且这些值出现在 t2
的 frase
中,我想将 x、y 和 z 与 caracter
.
t1
t2
这应该是结果
t1
我尝试使用游标,但它不起作用,因为我在 set 处引用错误,之前我尝试使用 while 循环,但结果相同。
DECLARE @frase VARCHAR (100)
DECLARE MICURSOR CURSOR FOR SELECT caracter FROM t1
OPEN MICURSOR
FETCH NEXT FROM MICURSOR
WHILE @@fetch_status = 0
BEGIN
SELECT t1.caracter FROM t1 INNER JOIN t2
ON t2.frase LIKE CONCAT('%', t1.caracter,'%')
UPDATE t1 SET caracter= 'caracter' + '(@frase-1)'
FETCH NEXT FROM MICURSOR INTO @frase
END
CLOSE MICURSOR
DEALLOCATE MICURSOR
希望这能达到目的,您必须利用 lead() 聚合函数来获取下一行。您可以在 dbfiddle link 中找到完整的解决方案,其中包含 table 和填充的记录以演示查询的工作原理。该解决方案适用于 SQLSEVER 2019。
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=71510d727bb04478383887e2e8ab3a52
update t1 set t1.caracter = concat(t1.caracter,lg)
from
(select id_val,ver,caracter,lead(caracter) over (order by id_val) lg from t1) tab,t1
where lg in (select frase from t2)
and tab.caracter = t1.caracter;
delete from t1 where caracter in (select frase from t2);
select * from t1;
id_val ver caracter
1 abc abc
1 abc 3
1 abc x
1 abc 2
1 abc y
2 def def
2 def 5
2 def y
2 def 9
2 def z
应用脚本后的输出,
id_val ver caracter
1 abc abc
1 abc 3x
1 abc 2y
2 def def
2 def 5y
2 def 9z
我在尝试从 table t1
上传字段 caracter
时遇到问题。如果它出现在 t2
的 frase
中,我想将 caracter
的值与之前的值连接起来。例如,如果在 caracter
中找到 x、y 或 z,并且这些值出现在 t2
的 frase
中,我想将 x、y 和 z 与 caracter
.
t1
t2
这应该是结果
t1
我尝试使用游标,但它不起作用,因为我在 set 处引用错误,之前我尝试使用 while 循环,但结果相同。
DECLARE @frase VARCHAR (100)
DECLARE MICURSOR CURSOR FOR SELECT caracter FROM t1
OPEN MICURSOR
FETCH NEXT FROM MICURSOR
WHILE @@fetch_status = 0
BEGIN
SELECT t1.caracter FROM t1 INNER JOIN t2
ON t2.frase LIKE CONCAT('%', t1.caracter,'%')
UPDATE t1 SET caracter= 'caracter' + '(@frase-1)'
FETCH NEXT FROM MICURSOR INTO @frase
END
CLOSE MICURSOR
DEALLOCATE MICURSOR
希望这能达到目的,您必须利用 lead() 聚合函数来获取下一行。您可以在 dbfiddle link 中找到完整的解决方案,其中包含 table 和填充的记录以演示查询的工作原理。该解决方案适用于 SQLSEVER 2019。 https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=71510d727bb04478383887e2e8ab3a52
update t1 set t1.caracter = concat(t1.caracter,lg)
from
(select id_val,ver,caracter,lead(caracter) over (order by id_val) lg from t1) tab,t1
where lg in (select frase from t2)
and tab.caracter = t1.caracter;
delete from t1 where caracter in (select frase from t2);
select * from t1;
id_val ver caracter
1 abc abc
1 abc 3
1 abc x
1 abc 2
1 abc y
2 def def
2 def 5
2 def y
2 def 9
2 def z
应用脚本后的输出,
id_val ver caracter
1 abc abc
1 abc 3x
1 abc 2y
2 def def
2 def 5y
2 def 9z