繁体   English   中英

将多行合并为不同的表

[英]Combine multiple rows into one row,different table

我有如下表:

店铺表:

ShopID | PersonID
-----------------
  1    |  10001
  2    |  10002
  2    |  10003

人表

PersonID | PersonName
---------------------
  10001  | Alex
  10002  | John
  10003  | William

之后,我要按ShopID分组。 我的预期结果如下:

ShopID | PersonName
--------------------
  1    |    Alex
  2    | John / William

我尝试参考:将多行合并为一行 http://www.mssqltips.com/sqlservertip/2914/rolling-up-multiple-rows-into-a-single-row-and-column-for-sql-server-data/ 但这不是我想要的。

如何将多行合并为另一张表中的一行?

检出for xml选项以连接结果。 stuff函数用于删除正斜杠的第一个实例,而xml.value函数用于防止&, <, >和其他特殊字符被XML嵌入到&amp; &gt; &lt; &amp; &gt; &lt;

我的原始答案查询中有一个错误,这是编辑后的版本:

Select s.shopid, 
Stuff (
(
    select ' / '  + p.personName 
    from person p 
    inner join shop s2 on s2.personID = p.personID
    where s2.shopID = s.shopID
    For xml path(''), TYPE --for xml to place everything under node '', which will concatenate the results.
) 
.value('.','NVARCHAR(MAX)') --this is used to convert the XML to nvarchar(max), so that &, <, >, and other special chars do not get XML encoded.
, 1,3,'') --use stuff to replace first 3 characters with empty string.
as PersonName
From shop s
Group by s.shopid 
;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM