有2个SQL Server表:
产品:
Name Status Code
------------------------------------
Product 1 1001, 1003
Product 2 1001, 1005, 1006
状态:
Code Description
------------------------------------
1001 State A
1003 State B
1005 State C
1006 State D
...
我希望得到类似的内容:
Product Status
---------------------------------------------
Product 1 State A, State B
Product 2 State A, State C, State D
答案 0 :(得分:1)
您可以使用如下查询:
的 See working demo 强>
create table Products (Name varchar(100), [Status Code] varchar(100));
insert into Products values
('Product 1', '1001, 1003')
,('Product 2', '1001, 1005, 1006');
create table [Status] (Code varchar(100), Description varchar(100));
insert into [Status] values
('1001', 'State A')
,('1003', 'State B')
,('1005', 'State C')
,('1006', 'State D')
; WITH X AS
(
SELECT
P1.Name,
S.Description
FROM
(
SELECT *,
cast('<X>'+replace(P.[Status Code],',','</X><X>')+'</X>' as XML) AS xmlprods FROM Products P
)P1
CROSS APPLY
(
SELECT fdata.D.value('.','varchar(100)') AS splitdata
FROM P1.xmlprods.nodes('X') AS fdata(D)) O
LEFT JOIN [Status] S
ON S.Code= LTRIM(RTRIM(O.splitdata ))
)
SELECT
Name,
Description= STUFF((
SELECT ',' + Description FROM x AS x2
WHERE x2.Name = x.Name
ORDER BY Name FOR XML PATH,
TYPE).value(N'.[1]',N'varchar(max)'), 1, 1, '')
FROM
X
GROUP BY Name
答案 1 :(得分:0)
你可以试试这个。我使用了临时表,但你可以使用任何你想要的方法
SELECT p.Product,p.Status,s.Description INTO #tmp FROM( SELECT Name Product,TRIM(value)Status FROM tblProduct CROSS 申请STRING_SPLIT(TRIM(StatusCode),&#39;,&#39;))p JOIN tblStatus s ON s.Code = p.Status
选择不同的产品 , 东西(( 选择&#39;,&#39; + tmp2.Description 来自#tmp tmp2 其中tmp2.Product = tmp1.Product 按tmp2.Product排序 用于xml路径(&#39;&#39;) ),1,1,&#39;&#39;)作为StatusCode来自#tmp tmp1 group by Product
答案 2 :(得分:0)
查询下方将有助于将任何逗号分隔为列表。
SELECT A.OtherID,
Split.a.value('.', 'VARCHAR(100)') AS Data
FROM
(
SELECT OtherID,
CAST ('<M>' + REPLACE(Data, ',', '</M><M>') + '</M>' AS XML) AS Data
FROM Table1
) AS A CROSS APPLY Data.nodes ('/M') AS Split(a)