从另一个表中选择多值并将一个字符串拆分为 -

时间:2015-07-11 06:44:56

标签: sql-server select view

我在MS SQL Server中有2个表。

表1

ID   Name  
-------------
10   Series      
11   Movie      
12   Music      
13   Other     

表2

ID    IDCatg    Value  
---------------------------
1       10          Hannibal
2       10          Blacklist
3       10          POI
4       11          Hitman
5       11          SAW
6       11          Spider man
7       12          taylor swift
8       12          britney spears

我想通过表2中的IDCatg进行选择,并在表1中创建一个新列,如下所示:

IDCatg     Name        Value
--------------------------------------------
10         Series      Hannibal-Blacklist-POI
11         Movie       Hitman-SAW-Spider man
12         Music       taylor swift-britney spears

我如何通过观看来做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用STUFF执行此操作:

SELECT T21.IDCatg, T1.Name,
      [Value] = STUFF((
          SELECT '-' + T22.[Value]
          FROM Table2 T22
          WHERE T21.IDCatg = T22.IDCatg
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM Table2 T21 JOIN 
     Table1 T1 ON T1.ID=T21.IDCatg
GROUP BY T21.IDCatg,T1.Name

结果:

IDCatg  Name    Value
---------------------------------------------
10      Series  Hannibal-Blacklist-POI
11      Movie   Hitman-SAW-Spider man
12      Music   taylor swift-britney spears

SQL Fiddle

中的示例结果

修改

Value的类型为int时,您可以将其强制转换为varchar:

  [Value] = STUFF((
      SELECT '-' + CAST(T22.[Value] AS Varchar(MAX))