我在示例中遇到了问题
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)
----------
答案 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
对于MySQL:
SELECT id,GROUP_CONCAT(name SEPARATOR ' - ') as name
FROM TableName
GROUP BY id
结果:
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;