sql - 解析子查询中的拆分字符串

标签 sql sql-server tsql split

我在 Microsoft SQL 数据库中有两个表,一个包含 3 列,这些列具有分隔值(通过逗号和/或斜杠,但两者都应被视为分隔符)。 然后我有另一个表,其中包含一个 ID,该 ID 与 TABLE1 的拆分字符串中的每个项目相同。 我想解析 TABLE 1 中的项目,以便显示 TABLE2 中匹配行的文本。 有办法实现吗?

表 1

Text1           Text2           Text3
TA12,TA250      T1  
TA12,TA250      T1  
TA12,TA250      TA250,TA12      T310/T52
TA12,TA250      TA250           T310/T52

表 2

TA12            Hello
TA250           World
T1              This is a Test
T310            You are
T52             a Hero

期望的结果

Text1           Text2           Text3
Hello World     This is a Test  NULL
Hello World     This is a Test  NULL
Hello World     World Hello     You are a Hero
Hello World     World           You are a Hero

我可以使用 C# 实现这一点,但我更希望它发生在 SQL 端。

最佳答案

在最新版本的 SQL Server 中,您可以:

select t.*, t1.new_text1, t2.new_text2, t3.new_text3
from table1 t outer apply
     (select string_agg(t2.col2) as new_text1
      from table2 t2
      where t2.col1 in (select * from string_split(replace(t.text1, '/', ','), ','))
     ) t1 outer apply
     (select string_agg(t2.col2) as new_text2
      from table2 t2
      where t2.col1 in (select * from string_split(replace(t.text2, '/', ','), ','))
     ) t2 outer apply
     (select string_agg(t2.col2) as new_text3
      from table2 t2
      where t2.col1 in (select * from string_split(replace(1.text3, '/', ','), ','))
     ) t3;

也就是说,修复数据模型应该优先于尝试使用它。

关于sql - 解析子查询中的拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57473373/

相关文章:

sql-server - 规范化表格

多条语句的 PHP oci_execute

mysql - 在 MySQL 中连接两个子查询

sql - % 在 like 子句的开头

php - SQL 顺序 - 两个不同的表具有一个相同的键

sql - 按列分组,选择最新值

sql - 如何在日期时间翻转月份和日期?

MySQL 根据找到的 ID 返回 1 或 0

sql - 如何使用SQL为子项目创建序列号?

sql-server - SQL Server 作业动态调度