mysql - 将列分成行(数据透视表?)

标签 mysql sql

给定一个表格行,例如:

id  |  username  |  att7  |  att28  |  atttotal
1   |   12345    |   77   |    88   |     99

SQL 中有没有一种方法(我现在使用 MySQL,但实际上可以是任何数据库)来转换它,以便我的 VIEW 中的输出类似于:

id  |  username  |  type  |  period      | value
1   |   12345    |   Att  |    7 Days    |  77
2   |   12345    |   Att  |    28 Days   |  88
3   |   12345    |   Att  |    Total     |  99

我现在正在阅读有关数据透视表的内容,因为我觉得这可能是所需要的,但到目前为止我还无法弄清楚我实际上会如何解决这个问题..

干杯。

最佳答案

这是一个逆透视。最简单的方法是使用 union all:

create view v as
    select id, username, 'Att' as type, '7 days' as period, att7 from table union all
    select id, username, 'Att' as type, '28 days' as period, att28 from table union all
    select id, username, 'Att' as type, 'total' as period, total from table;

如果您的表很大,则可以使用更有效的方法来编写此类查询。

关于mysql - 将列分成行(数据透视表?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22537539/

相关文章:

php - 限制 WordPress 用户每日门票配额

mysql - SQL - OUTER JOIN a UNION-ed 表

mysql - ORDER BY NULL 比 ORDER BY 列慢

php - php寻呼机代码中检索sql查询错误

javascript - 如何处理交易错误?

php内存限制垃圾收集器

MySQL 时区

mysql - SQL查询FOR中的动态表名

c# - 如何修复 "Incorrect syntax near ' )'"。当查询中没有 ) 时

php - 如何防止 PHP 中的 SQL 注入(inject)?