我要完成一个艰巨的任务,要建立一个从表中检索的数组,该数组类似于以下内容:
table_a
id | scenario_id | entity_id
1 1;2;3;4;5 1;3
2 4;5;8;10 2;3
3 1;5;8;11 1;2;4;
4 3;5;8;9 4;5;
现在,如果一个用户从一个entity_id中进行选择,假设为3,则SQL查询应返回类似以下内容:
scenario_id
1;2;3;4;5;8;10
或者,如果他选择5,则返回的数组应类似于:
scenario_id
3;5;8;9
可以仅使用SQL语句来完成吗?
对于SQL Server,您可以使用此命令获得所需的输出:
DECLARE @xml xml, @entity_id int = 3
--Here I generate data similar to yours
;WITH cte AS (
SELECT *
FROM (VALUES
(1, '1;2;3;4;5', '1;3'),
(2, '4;5;8;10', '2;3'),
(3, '1;5;8;11', '1;2;4;'),
(4, '3;5;8;9', '4;5;')
) as t(id, scenario_id, [entity_id])
)
--create xml
SELECT @xml = (
SELECT CAST('<i id="'+ CAST(id as nvarchar(10)) +'"><s>' + REPLACE(scenario_id,';','</s><s>') + '</s><e>' + REPLACE([entity_id],';','</e><e>') + '</e></i>' as xml)
FROM cte
FOR XML PATH('')
)
--Normalizing the table and getting result
SELECT STUFF((
SELECT ';' + CAST(scenario_id as nvarchar(10))
FROM (
SELECT DISTINCT t.v.value('.','int') as scenario_id
FROM @xml.nodes('/i/s') as t(v)
INNER JOIN @xml.nodes('/i/e') as s(r)
ON t.v.value('../@id','int') = s.r.value('../@id','int')
WHERE s.r.value('.','int') = @entity_id
) as p
FOR XML PATH('')),1,1,'') as scenario_id
输出为entity_id = 3
:
scenario_id
1;2;3;4;5;8;10
对于 entity_id = 5
scenario_id
3;5;8;9
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句