【问题标题】:Combine multiple rows into one row,different table将多行合并为一行,不同的表
【发布时间】:2014-01-27 22:46:37
【问题描述】:

我有如下表:

商店表:

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

人员表

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

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

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

我已尝试参考:Combine multiple rows into one row。和http://www.mssqltips.com/sqlservertip/2914/rolling-up-multiple-rows-into-a-single-row-and-column-for-sql-server-data/。但这不是我想要的。

如何将多行合并为不同表中的一行?

【问题讨论】:

  • 每间店铺最多可容纳多少人?
  • 你试过了吗?什么不起作用。

标签: sql sql-server sql-server-2008-r2


【解决方案1】:

查看for xml 选项以连接结果。 stuff 函数用于删除第一个正斜杠实例,xml.value 函数用于防止&, <, > 等特殊字符被XML endoded 到& > < 等。

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

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 
;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2018-07-05
    • 2012-12-29
    • 1970-01-01
    相关资源
    最近更新 更多