栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

MySQL查询在两列的基础上将行动态转换为列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MySQL查询在两列的基础上将行动态转换为列

如果你有值的已知数量的两个

order
item
,那么你可以硬编码查询到:

select id,  max(case when `order` = 1 then data end) order1,  max(case when `order` = 2 then data end) order2,  max(case when `order` = 3 then data end) order3,  max(case when item = 1 then price end) item1,  max(case when item = 2 then price end) item2,  max(case when item = 3 then price end) item3,  max(case when item = 4 then price end) item4from tableAgroup by id;

参见演示。但是您将要遇到的部分问题是因为您试图转换多列数据。我建议获得最终结果的方法是先取消数据透视。MySQL没有取消透视功能,但是您可以使用UNIOn
ALL将多对列转换为行。要取消透视的代码将类似于以下内容:

select id, concat('order', `order`) col,  data valuefrom tableAunion allselect id, concat('item', item) col, price valuefrom tableA;

参见演示。其结果将是:

| ID |    COL | VALUE |-----------------------|  1 | order1 |     P ||  1 | order1 |     P ||  1 | order1 |     P ||  1 |  item1 |    50 ||  1 |  item2 |    60 ||  1 |  item3 |    70 |

如您所见,这占用了

order
/
data
item
/
的多个列,
price
并将其转换为多行。一旦完成,您就可以使用带有CASE的聚合函数将值转换回列:

select id,   max(case when col = 'order1' then value end) order1,  max(case when col = 'order2' then value end) order2,  max(case when col = 'order3' then value end) order3,  max(case when col = 'item1' then value end) item1,  max(case when col = 'item2' then value end) item2,  max(case when col = 'item3' then value end) item3from(  select id, concat('order', `order`) col,  data value  from tableA  union all  select id, concat('item', item) col, price value  from tableA) dgroup by id;

参见演示。最后,您需要将以上代码转换为动态的预处理语句查询:

SET @sql = NULL;SELECt  GROUP_CONCAt(DISTINCT    CONCAt(      'max(case when col = ''',      col,      ''' then value end) as `',       col, '`')  ) INTO @sqlFROM(  select concat('order', `order`) col  from tableA  union all  select concat('item', `item`) col  from tableA)d;SET @sql = CONCAt('SELECt id, ', @sql, '        from       (         select id, concat(''order'', `order`) col,  data value         from tableA         union all         select id, concat(''item'', item) col, price value         from tableA       ) d       group by id');PREPARE stmt FROM @sql;EXECUTE stmt;DEALLOCATE PREPARE stmt;

请参阅带有演示的SQL Fiddle。结果如下:

| ID | ORDER1 | ORDER2 | ORDER3 | ITEM1 | ITEM2 |  ITEM3 |  ITEM4 |-------------------------------------------------------------------|  1 |      P |      Q | (null) |    50 |    60 |     70 | (null) ||  2 |      P | (null) |      S |    50 |    60 | (null) |     80 |


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380223.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号