如何在一列中加入值? (SQL 服务器 2008R2)
How to join values in one column? (SQL Server 2008R2)
我不知道如何在标题中简短地描述我的问题,但我希望有人能理解并能帮助我:)
在我的例子中,我加入了 2 个表:
SELECT t1.Name, t1.Group
FROM tblOne AS t1
UNION
SELECT t2.Name, t2.Group
FROM tblTwo AS t2
结果:
=====================
Name | Group
=====================
Miller | TST
Miller | DEV
Johnson | TST
White | TST
Lopez | DEV
Brown | TST
Jackson | DEV
Jackson | TST
目标:
Name | Group
=====================
Miller | DEV, TST
Johnson | TST
White | TST
Lopez | DEV
Brown | TST
Jackson | DEV, TST
有人有想法吗?
预先感谢任何提示。
您可以使用非常简单的 xml
方法和 stuff()
函数:
select t1.name, stuff((select distinct ','+t2.[group]
from table2 t2
where t2.name = t1.name
for xml path('')
), 1, 1, ''
) as [group]
from table1 t1
group by name;
您 可以 使用 FOR XML
但如果您的数据与示例中的数据相同,那么您还可以进行更简单的查询,例如:
SELECT
ISNULL(t1.[Name], t2.[Name]) AS [Name],
ISNULL(t1.[Group] + CASE WHEN t2.[Group] IS NOT NULL THEN ',' ELSE '' END, '')
+ ISNULL(t2.[Group], '') AS [Group]
FROM
tblOne AS t1
FULL OUTER JOIN tblTwo AS t2 ON t2.[Name] = t1.[Name];
这假设每个 "Name" 存在:
- 仅在 tblOne 中;
- 仅在 tblTwo 中;
- 在 tblOne 和 tblTwo 中恰好一次。
如果上述逻辑不正确,那么您需要 XML 版本。
此外,我不得不说,使用 [Name]
和 [Group]
等保留名称作为列名可能不是一个好主意(特别是 [Group]
!)?
我相信你需要:
with t as (
select t1.Name, Group as grp
from tblOne
union
select t2.Name, Group as grp
from tblTwo t2
)
select name,
stuff( (select ',' + grp
from t t2
where t2.name = t.name
for xml path ('')
), 1, 1, ''
) as groups
from (select distinct name from t) t;
我不知道如何在标题中简短地描述我的问题,但我希望有人能理解并能帮助我:)
在我的例子中,我加入了 2 个表:
SELECT t1.Name, t1.Group
FROM tblOne AS t1
UNION
SELECT t2.Name, t2.Group
FROM tblTwo AS t2
结果:
=====================
Name | Group
=====================
Miller | TST
Miller | DEV
Johnson | TST
White | TST
Lopez | DEV
Brown | TST
Jackson | DEV
Jackson | TST
目标:
Name | Group
=====================
Miller | DEV, TST
Johnson | TST
White | TST
Lopez | DEV
Brown | TST
Jackson | DEV, TST
有人有想法吗? 预先感谢任何提示。
您可以使用非常简单的 xml
方法和 stuff()
函数:
select t1.name, stuff((select distinct ','+t2.[group]
from table2 t2
where t2.name = t1.name
for xml path('')
), 1, 1, ''
) as [group]
from table1 t1
group by name;
您 可以 使用 FOR XML
但如果您的数据与示例中的数据相同,那么您还可以进行更简单的查询,例如:
SELECT
ISNULL(t1.[Name], t2.[Name]) AS [Name],
ISNULL(t1.[Group] + CASE WHEN t2.[Group] IS NOT NULL THEN ',' ELSE '' END, '')
+ ISNULL(t2.[Group], '') AS [Group]
FROM
tblOne AS t1
FULL OUTER JOIN tblTwo AS t2 ON t2.[Name] = t1.[Name];
这假设每个 "Name" 存在:
- 仅在 tblOne 中;
- 仅在 tblTwo 中;
- 在 tblOne 和 tblTwo 中恰好一次。
如果上述逻辑不正确,那么您需要 XML 版本。
此外,我不得不说,使用 [Name]
和 [Group]
等保留名称作为列名可能不是一个好主意(特别是 [Group]
!)?
我相信你需要:
with t as (
select t1.Name, Group as grp
from tblOne
union
select t2.Name, Group as grp
from tblTwo t2
)
select name,
stuff( (select ',' + grp
from t t2
where t2.name = t.name
for xml path ('')
), 1, 1, ''
) as groups
from (select distinct name from t) t;