使用多个重复观测值在SQL中转置数据

问题描述

我有一个要从长到宽转置的数据集。我有:

 **ID         **Question**        Answer**
   1            Follow-up to         a
   1            Follow-up to         a
   1            Follow-up to         b
   1            Follow-up to         c
   2            Follow-up to         b
   2            Follow-up to         c
   4            Follow-up to         a
   4            Follow-up to         b
   4            Follow-up to         b
   6            Follow-up to         a

我想要的数据集看起来像这样:

**ID         **Follow-up to**
  1              a,b,c
  2              b,c
  4              a,b
  6              a

我希望每个ID的多个响应都显示在同一行中,并且希望删除每个ID的重复响应。我使用第一个使它在SAS中工作。最后。功能,但我不确定如何在SQL中完成此功能。数据集具有成千上万的行,其中包含数十个变量,就像上面的“跟进”示例一样。当前,我正在使用json功能以宽格式转置和提取我想要的所有变量,但是转换只为每个ID携带1个答案,而我需要所有这些都以新格式继续

谢谢。

解决方法

您要字符串聚合,然后struct Information { struct Score { struct Score *link; float src; } *src; }; 。在标准SQL中,您可以这样写:

distinct

不同的数据库产品可能使用另一个函数进行字符串聚合(SQL Server具有select id,listagg(distinct answer) within group(order by answer) follow_up_to from mytable group by id ,MySQL具有string_agg(),依此类推)-但逻辑是相同的。

在Postgres中:

group_concat()
,

如果您使用的是Oracle,则上面的查询将无法工作,因为listagg内不允许使用不同的查询:

WITH CTE1 as 
(select distinct id,answer from TABLE1)
SELECT ID,LISTAGG(ANSWER,',') WITHIN GROUP(ORDER BY ANSWER)
FROM CTE1 GROUP BY ID;
,

您似乎想要:

select id,string_agg(distinct answer,') as answers
from t
group by id;

请注意,我强烈建议在结果列中使用数组而不是字符串,但是您似乎指定了字符串。同样,字符串中值的顺序是任意的。数据中没有任何列可指定顺序。如果这样做,则可以在聚合函数中添加一个order by

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...