SQL:从 2 列数据源创建聚合 table

SQL: Creating an aggregated table from a 2-column data source

我在数据库中有一个 table,我想将其中的问题和答案聚合成更易读的数据 table。来源table

+-----+----------------+----------------------------+----------------+
| QID | Date Submitted |          Question          |     Answer     |
+-----+----------------+----------------------------+----------------+
|   0 | 08/04/2021     | companyName                | Yaneev         |
|   1 | 08/04/2021     | humanRightPolicy           | George Micheal |
|   2 | 08/04/2021     | accountManagerMobileNumber | 7474236843     |
|   3 | 08/04/2021     | swiftCode                  | AOEU326        |
|   4 | 03/04/2021     | companyName                | Eimbee         |
|   5 | 03/04/2021     | humanRightPolicy           | Revvie George  |
|   6 | 03/04/2021     | accountManagerMobileNumber | 7475123843     |
|   7 | 03/04/2021     | swiftCode                  | AOEU324        |
|   8 | 04/04/2021     | companyName                | Yaneev         |
|   9 | 04/04/2021     | humanRightPolicy           | Mark Fox       |
|  10 | 04/04/2021     | accountManagerMobileNumber | 74742121231    |
|  11 | 04/04/2021     | swiftCode                  | 124eoKK        |
+-----+----------------+----------------------------+----------------+

我希望 'destination' table 看起来像

+--------------+-------------------+----------------------------+-----------+
| Company Name | humanRightsPolicy | accountManagerMobileNumber | swiftCode |
+--------------+-------------------+----------------------------+-----------+
| Yaneev       | George Micheal    |                 7474236843 | AOEU326   |
| Eimbee       | Revvie George     |                 7475123843 | AOEU324   |
+--------------+-------------------+----------------------------+-----------+

我也很想知道这是个什么操作,因为我觉得这不是什么新鲜事

SQL table 表示 无序 集合。让我假设您有一个排序列。有了这样一列,你可以为同一公司的每组行分配一个组,然后使用条件聚合:

select max(case when question = 'Company Name' then answer end) as company_name,
       max(case when question = 'Q1' then answer end) as q1,
       max(case when question = 'Q2' then answer end) as q2,
       max(case when question = 'Q3' then answer end) as q3       
from (select t.*,
             sum(case when question = 'Company Name' then 1 else 0 end) over (order by <ordering col>) as grp
      from t
     ) t
group by grp;

请注意,这回答了您提出的问题,其中所有问题都是已知的——因此结果列都是已知的。如果您事先不知道问题,则需要使用动态 SQL(即将查询构造为字符串,然后执行)。如何做到这一点完全取决于您使用的数据库。

编辑:

在 MySQL 的旧版本中,您可以使用子查询:

select max(case when question = 'Company Name' then answer end) as company_name,
       max(case when question = 'Q1' then answer end) as q1,
       max(case when question = 'Q2' then answer end) as q2,
       max(case when question = 'Q3' then answer end) as q3       
from (select t.*,
             (select count(*)
              from t t2
              where t2.question = 'Company Name' and
                    t2.<ordering col> <= t.<ordering col>
             ) as grp
      from t
     ) t
group by grp;