如何创建查询以将两行或三行组合为重复的ID

时间:2017-10-18 15:52:54

标签: sql sql-server

我正在尝试创建一个select语句来组合任何特定列上重复ID的值。

我的表是:

ID   Name
---------
01   A
01   B
02   C
03   D

如何选择获取以下值:01 A,B代表ID:01。目前,当我使用Table *中的Select *时,它列出了两行的01 ID。我喜欢将它组合成一行,Name应该与任何重复行的逗号结合使用。

新代码:

select Name, ID = REPLACE
  ((select Surname AS [data()]
        FROM Mytable
        WHERE Name = d. Name
        ORDER BY Name FOR XML path('')), ' ', REQUIRED SEPERATOR)
FROM Mytable d
WHERE Name IS NOT NULL
GROUP BY Name

非常感谢!

1 个答案:

答案 0 :(得分:1)

SQL Fiddle

MS SQL Server 2014架构设置

create table t (id int not null, name nvarchar(max) not null)
insert t (id, name) values 
  (1, 'A'), 
  (1, 'B'),
  (1, 'C'), 
  (2, 'A'),
  (2, 'D'), 
  (3, 'A'),
  (3, 'F'), 
  (3, 'E')

查询1

    select id, REPLACE
      ((select name AS [data()]
            FROM t as t1
            WHERE t1.id = t0.id
            ORDER BY Name FOR XML path('')), ' ', ',')
    FROM t as t0
    GROUP BY id

<强> Results

| id |       |
|----|-------|
|  1 | A,B,C |
|  2 |   A,D |
|  3 | A,E,F |

<强>更新 为了处理名称中已经存在的空格,我们可以在分组之前将它们替换为下划线,并在之后替换为:

  select id, replace(REPLACE
  ((select replace(name, ' ', '_') AS [data()]
        FROM t as t1
        WHERE t1.id = t0.id
        ORDER BY Name FOR XML path('')), ' ', ','), '_', ' ')
FROM t as t0
GROUP BY id