mysql - 将动态列转换为行

标签 mysql unpivot

我想知道如何将 Table_1 转为 Expected_Result_Table:

Table1
-----------------------------------------
Id       abc  brt ccc ddq eee fff gga hxx
-----------------------------------------
12345     0    1   0   5   0   2   0   0  
21321     0    0   0   0   0   0   0   0   
33333     2    0   0   0   0   0   0   0   
41414     0    0   0   0   5   0   0   1   
55001     0    0   0   0   0   0   0   2   
60000     0    0   0   0   0   0   0   0 
77777     9    0   3   0   0   0   0   0
Expected_Result_Table
---------------------
Id      Word   Qty>0
---------------------
12345    brt    1
12345    ddq    5
12345    fff    2
33333    abc    2
41414    eee    5
41414    hxx    1
55001    hxx    2
77777    abc    9
77777    ccc    3

那么,如何转置 Table_1 中的列导致 Expected_Result_Table,只考虑 > 0 的值?

最佳答案

MySQL 没有 UNPIVOT 函数,但您可以使用 UNION ALL 将列转换为行。

基本语法是:

select id, word, qty
from
(
  select id, 'abc' word, abc qty
  from yt
  where abc > 0
  union all
  select id, 'brt', brt
  from yt
  where brt > 0
) d
order by id;

在您的情况下,您声明需要针对动态列的解决方案。如果是这种情况,那么您将需要使用准备好的语句来生成动态 SQL:

SET @sql = NULL;

SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'select id, ''',
      c.column_name,
      ''' as word, ',
      c.column_name,
      ' as qty 
      from yt 
      where ',
      c.column_name,
      ' > 0'
    ) SEPARATOR ' UNION ALL '
  ) INTO @sql
FROM information_schema.columns c
where c.table_name = 'yt'
  and c.column_name not in ('id')
order by c.ordinal_position;

SET @sql 
  = CONCAT('select id, word, qty
           from
           (', @sql, ') x  order by id');


PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

参见 SQL Fiddle with Demo

关于mysql - 将动态列转换为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16359345/

相关文章:

oracle - 逆透视表脚本错误

mysqldump 创建表而不是 View

php - 在应用程序中记录用户事件

sql - Hive - Hive 中的 Unpivot 功能

mysql - SQL从多列转换为少列?

SQL:是否有一种巧妙的方法可以在不使用内部查询或聚合函数的情况下在数据透视列中显示文本数据?

mysql - 我想要一个 mysql 查询。所有包含大写字母的字段

Mysql查询优化——sum()函数

php - mysqli fetch_assoc() 未发布

mysql - 如何组合多个查询