【问题标题】:Transposing data in SQL with multiple and duplicate observations在 SQL 中转置具有多个和重复观察的数据
【发布时间】:2020-12-16 08:30:26
【问题描述】:

我有一个数据集,我想将其从长转换为宽。我有:

 **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 个答案,而我需要所有这些都以新格式携带.

提前谢谢你。

【问题讨论】:

  • 请用您正在运行的数据库标记您的问题:mysql、oracle、sql-server...?

标签: sql string postgresql group-by string-aggregation


【解决方案1】:

如果您使用的是 Oracle,那么上述查询将无法正常工作,因为 listagg 中不允许使用 distinct:

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

【讨论】:

    【解决方案2】:

    你似乎想要:

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

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

    【讨论】:

      【解决方案3】:

      您想要字符串聚合和distinct。在标准 SQL 中,您可以这样表述:

      select id, listagg(distinct answer) within group(order by answer) follow_up_to
      from mytable
      group by id
      

      不同的数据库产品可能会使用另一个函数进行字符串聚合(SQL Server 有string_agg(),MySQL 有group_concat(),等等)——但逻辑是一样的。

      在 Postgres 中:

      select id, string_agg(distinct answer, ',' order by answer) follow_up_to
      from mytable
      group by id
      

      【讨论】:

      • 这在 Oracle 中不起作用,因为 listagg 中不允许有不同的内容。
      • 这是一个 postgres SQL 数据库。
      • 感谢小巴的回复。尝试您建议的代码时出现以下错误:错误:无法将 DISTINCT 与 WITHIN GROUP 一起使用。鉴于我正在运行 postgres sql,您有什么建议吗?非常感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多