简体   繁体   English

MYSQL-数据透视

[英]MYSQL - Pivoting Data

The data from my application currently comes in as a series of columns, but I would really like there to only be two columns, RESULTS and TASK. 我的应用程序中的数据当前以一系列列的形式出现,但是我真的希望只有两列,即RESULTS和TASK。 See the attached "Spreadsheet" screenshot for how my current data comes in and the "Database" Screenshot for what I am trying to achieve. 有关我当前数据的输入方式,请参见附件的“电子表格”屏幕截图,有关我要实现的目标,请参见“数据库”屏幕截图。

I am currently able to do this with about 100 UNION ALL statements, but my queries become DREADFULLY slow. 我目前能够使用大约100条UNION ALL语句来执行此操作,但是我的查询的执行速度为DREADFULLY缓慢。 Is there a better way to achieve this without so many UNION ALLs? 没有那么多的UNION ALL,有没有更好的方法来实现这一目标?

试算表 Database: 数据库:

数据库

Thanks! 谢谢!

UNION ALL is a fine approach, but it does require scanning the table once for each subquery. UNION ALL是一种很好的方法,但是它确实需要为每个子查询扫描一次表。

One alternative uses a cross join . 一种选择是使用cross join This requires more coding, but it might speed things up: 这需要更多的编码,但是可能会加快速度:

select tt.task,
       (case when tt.task =  'Use Proper PPE' then use_proper_ppe
             when tt.task = 'Damage Prevention' then damage_prevention
             . . .
        end) as result
from t cross join
     (select 'Use Proper PPE' as task union all
      select 'Damage Prevention' union all
      . . .
     ) tt;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM