简体   繁体   中英

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. 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. Is there a better way to achieve this without so many UNION ALLs?

试算表 Database:

数据库

Thanks!

UNION ALL is a fine approach, but it does require scanning the table once for each subquery.

One alternative uses a 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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