【问题标题】:How do you transpose a table in a generalizable way in SQL?如何在 SQL 中以可通用的方式转置表?
【发布时间】:2016-12-10 14:03:36
【问题描述】:

您将如何转置此表:

old_table

+----+--------+-------------+-------------------+
| id | type   | field       | value             |
+----+--------+-------------+-------------------+
| 1  | person | gender      | female            |
+----+--------+-------------+-------------------+
| 1  | person | age         | 22                |
+----+--------+-------------+-------------------+
| 1  | person | name        | Julie Smith       |
+----+--------+-------------+-------------------+
| 1  | person | picture_url | www.pic.com/1.jpg |
+----+--------+-------------+-------------------+
| 2  | person | gender      | male              |
+----+--------+-------------+-------------------+
| 2  | person | name        | Johnny Parsons    |
+----+--------+-------------+-------------------+

到这样的表中:

new_table

+----+----------------+--------+------+-------------------+
| id | name           | gender | age  | picture_url       |
+----+----------------+--------+------+-------------------+
| 1  | Julie Smith    | female | 22   | www.pic.com/1.jpg |
+----+----------------+--------+------+-------------------+
| 2  | Johnny Parsons | male   | Null | Null              |
+----+----------------+--------+------+-------------------+

我们可以这样查询:

INSERT INTO new_table SELECT
id::id as id,
max(case when field='name' then value else null end) as name,
max(case when field='gender' then value else null end) as gender,
max(case when field='age' then value else null end) as age,
max(case when field='picture_url' then value else null end) as picture_url
FROM old_table
WHERE 1=1
AND type = 'person'
GROUP BY
id
;

不幸的是,此查询不可推广,如果我要添加新字段,那么这些字段将不会添加到新表中。有没有办法编写更通用的查询?

【问题讨论】:

  • 动态添加字段或表将采用动态生成的SQL。您将需要一个存储过程(或其他一些脚本语言)来处理新字段的添加和插入。
  • 此任务有时称为“透视”。在 MySQL 中,这是一个臭名昭著的痛苦。其他一些表服务器提供查询语法来支持数据透视。

标签: mysql sql postgresql transpose


【解决方案1】:

PIVOT(PostgreSQL 中的CROSSTAB)可能是您想要使用的。您在查询中有效地模拟了PIVOT。但是,为此您需要知道您拥有的所有属性/列。

如果您事先不知道这些值,则可以通过编程方式构建此类 SQL(在客户端或某些数据库允许执行生成的字符串)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多