我有以下数据:
column1 column2
1 aaa
1 bbb
2 ccc
2 ddd
2 eee
预期输出应为每列1类型一行,其中包含所有column2数据,如下所示:
column1, column2
1, aaa|bbb
2, ccc|ddd|eee
如何获得此输出?
我使用下面的查询来获取此数据。
select sub_id,listagg(pack_name, '|') within group(order by sub_id) package_name
from Recon_Droppacks_Migration group by sub_id;
col1:sub_id
col2:pack_name
table:Recon_Droppacks_Migration
答案 0 :(得分:4)
您没有指定您正在使用的RDBMS。因此,您将在各种DBMS中执行此操作。
MySQL,您将使用GROUP_CONCAT()
:
SELECT column1, GROUP_CONCAT(column2 SEPARATOR ' | ') column2
FROM table1
GROUP BY column1
在SQL Server中,您将使用FOR XML PATH
:
select
t1.col1,
STUFF((SELECT distinct ' | ' + col2
from table1 t2
where t1.col1 = t2.col1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,3,' ') col2
from table1 t1
group by t1.col1
在Oracle中,您可以使用LISTAGG()
:
select "col1",
listagg("col2", ' | ') within group(order by "col1") col2
from table1
group by "col1"
在Postgresql中,您可以使用string_agg()
:
SELECT column1, string_agg(column2, ' | ') col2
FROM Table1
GROUP BY column1;
根据您的评论编辑,您将需要使用:
select sub_id, listagg(pack_name, ' | ') within group(order by sub_id) package_name
from Recon_Droppacks_Migration
group by sub_id;
答案 1 :(得分:1)
使用MySQL:使用GROUP_CONCAT
SELECT column1, GROUP_CONCAT(column2 SEPARATOR ' | ') as column2
FROM Table1
GROUP BY column1
使用SQL Server:
SELECT distinct column1, column2 =
STUFF((SELECT ' | ' + column2
FROM Table1 b
WHERE b.column1 = a.column1
FOR XML PATH('')), 1, 2, '')
FROM Table1 a
GROUP BY column1;
答案 2 :(得分:1)
使用递归查询:
SELECT *,
Row_number()
OVER (
PARTITION BY COLUMN1
ORDER BY COLUMN1 ) rn
INTO #TEMP1
FROM TABLE1;
WITH RECUR
AS (SELECT *,
Cast(COLUMN2 AS VARCHAR(MAX)) AS full_text
FROM #TEMP1
WHERE RN = 1
UNION ALL
SELECT t1.*,
Cast(t2.FULL_TEXT + ' | ' + t1.COLUMN2 AS VARCHAR(MAX))
FROM #TEMP1 t1
INNER JOIN RECUR t2
ON t1.COLUMN1 = t2.COLUMN1
AND t1.RN = t2.RN + 1)
SELECT t1.COLUMN1,
t1.FULL_TEXT
FROM RECUR t1
INNER JOIN (SELECT Max(RN) rn,
COLUMN1
FROM RECUR
GROUP BY COLUMN1) t2
ON t1.COLUMN1 = t2.COLUMN1
AND t1.RN = t2.RN
请参阅完整示例here
答案 3 :(得分:0)
此解决方案Does T-SQL have an aggregate function to concatenate strings?工作正常,因为它不会在xml字符上失败。
declare @Temp_Table table (column1 bigint, column2 nvarchar(max))
insert into @Temp_Table (column1, column2)
select 1, 'aaa' union all
select 1, 'bbb' union all
select 2, 'ccc' union all
select 2, 'ddd' union all
select 2, 'eee'
select distinct
t1.column1,
stuff(
(
select
' | ' + t2.column2
from @Temp_Table as t2
where t2.column1 = t1.column1
order by t2.column2 for xml path(''), type
).value('.', 'nvarchar(max)')
, 1, 3, '')
from @Temp_Table as t1
您也可以编写游标并使用变量技巧
答案 4 :(得分:-1)
请尝试下面的查询
SELECT concat(CONVERT(column1,char(8))," , ") AS id,group_concat(CONVERT(column2, CHAR(20)) separator '|') AS result FROM `tablename` WHERE 1 group by column1
此处concat
用于附加,
字段column1
,而CONVERT
用于将其转换为字符串,因为它可以更好地处理字符串。并且GROUP_CONCAT
用于将特定column1
的所有结果附加到给定的saperator。
感谢