我有表tableA如下:
+--------+----------------------+
| Id | Ref |
+--------+----------------------+
| 1 | RN1-102,RN2-103 |
| 2 | RN1-106 |
| 3 | RN2-203 |
| 4 | NULL |
| 5 | RN1-104|,RN2-107 |
| 6 | RN1-101,RN2-105 |
| 7 | RN1-100,RN2-109 |
+--------+----------------------+
我需要一个输出(来自tableA的不同参考),如下所示:
+--------------------+
| Distinct Ref data |
+--------------------+
| RN1-100 |
| RN1-101 |
| RN1-102 |
| RN1-104 |
| RN1-106 |
| RN2-103 |
| RN2-105 |
| RN7-107 |
| RN2-109 |
| RN2-203 |
+--------------------+
我尝试使用以下查询:
select distinct Ref from tableA
请帮帮我..
答案 0 :(得分:1)
尝试使用此
SELECT distinct Split.a.value('.', 'VARCHAR(100)') REF
FROM (select ID,Cast ('<M>'
+ replace(Replace(REF, ',', '</M><M>'),'&','&')
+ '</M>' AS XML) AS Data from #Table) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)
答案 1 :(得分:0)
此问题类似于我之前回答的this question。我在答案中提出了两种方法,一种是使用递归而不是。
但如果您已经有一个表存储了ref
个键,那么您有第三个选择:
create table ref_table (ref varchar(10), ref_name varchar(100), primary key (ref));
select
r.ref
from
ref_table r
where
EXISTS (
select 1
from tableA a
where a.ref like '%'+r.ref+'%' -- or ','+a.ref+',' like '%,'+r.ref+',%'
)
答案 2 :(得分:0)
SELECT distinct Split.a.value('.', 'VARCHAR(100)') REF
FROM (select ID,Cast ('<M>'
+ replace(Replace(REF, ',', '</M><M>'),'&','&')
+ '</M>' AS XML) AS Data from #Table) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)