sql查询从2行到1列中选择相同的列

时间:2014-06-24 09:46:53

标签: sql

我在示例中遇到了问题

RowNumber     id    name
------------------------------
1              1     txt1
---------------------------
2              1     txt2
----------
3              2     txt3 
----------
4              2     txt4
----------
5              2     txt5
----------

所以我需要查询给我结果像

RowNumber   ResultColumn
----------
1            (txt1 - txt2)
----------
2            (txt3 - txt4 - txt5)
----------

5 个答案:

答案 0 :(得分:2)

对于Postgres,您可以使用string_agg()

select id, 
       string_agg(name, ' - ' order by name)
from the_table
group by id
order by id

答案 1 :(得分:1)

如果您使用的是MySQL,则可以使用GROUP_CONCAT功能:

SELECT RowNumber, GROUP_CONCAT(name)
FROM T
GROUP BY id

答案 2 :(得分:0)

试试这个

<强> MYSQL

SELECT id,Group_Concat(name SEPARATOR " - ")
From Table1
Group By id

使用 Group_Concat

<强> Fiddle Demo

<强> MSSQL

SELECT id,
      name = STUFF((
          SELECT '- ' + convert(varchar(10),T2.name)
          FROM Table1 T2
          WHERE T1.id = T2.id
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM Table1 T1
GROUP BY id

<强> Fiddle Demo

答案 3 :(得分:0)

对于SQL Server:

SELECT id,
      name = STUFF((
          SELECT '-' + convert(varchar(10),T2.name)
          FROM TableName T2
          WHERE T1.id = T2.id
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM TableName T1
GROUP BY id
ORDER BY id,name

Fiddle Example

对于MySQL:

SELECT id,GROUP_CONCAT(name SEPARATOR ' - ') as name
FROM TableName
GROUP BY id

Fiddle Example

结果:

ID  NAME
1   txt1 - txt2
2   txt3 - txt4 - txt5

答案 4 :(得分:0)

如果是MySQL:

SELECT id, GROUP_CONCAT(name SEPARATOR " - " ORDER BY name) AS Result
FROM myTable
GROUP BY id;