开发者社区> 问答> 正文

将动态列转置为行

我想知道如何逆转置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 那么,如何只考虑值> 0 来转置Table_1结果in中的列Expected_Result_Table?

展开
收起
保持可爱mmm 2020-05-11 16:04:53 500 0
1 条回答
写回答
取消 提交回答
  • 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;来源:stack overflo

    2020-05-11 16:05:05
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载