如何用服务名称替换逗号分隔的ID

时间:2019-01-27 21:39:51

标签: sql sql-server

我在SQL报表中使用了不同的表。我想在列之一中显示服务名称。

我必须不得不从另一个表中获取名称。如何用服务名称替换逗号分隔的ID?

表1

IdPerson   Date          Services 
------------------------------------                                           
12345      01 01 2019    1,5,15,17

表2

IdServices      description
----------------------------
 1              service 1
 2              service 2
 3              service 3
. . .
17              service 17

预期输出如下:

ClientId    Date          Services 
----------------------------------------------------------------------
12345       01 01 2019    service 1,service 5, service 15, service 17

1 个答案:

答案 0 :(得分:0)

我已经解决了以下问题:


;WITH x AS 
(
  SELECT Table_1.ClientId, Table_2.IdServices, Table_2.description
  FROM Table_1   AS Table_1
  CROSS APPLY STRING_SPLIT(Table_1.Services, ',') AS s
  INNER JOIN Table_2 AS Table_2
  ON s.value = Table_2.IdServices
)
SELECT 
Table_1.ClientId,
Table_1.Date,
Table_1services.services AS Services
FROM  
  Table_1 
  LEFT JOIN 
       (
             SELECT ClientId, STUFF((
             SELECT '; '+ description  FROM x AS x2 
             WHERE x2.ClientId = x.ClientId
             ORDER BY IdServices FOR XML PATH, 
             TYPE).value(N'.[1]',N'varchar(max)'), 1, 1, '') AS "services"
             FROM x
             GROUP BY ClientId
       ) AS Table_1services ON Table_1.ClientId = Table_1services.ClientId