Mysql 动态转置复杂 sql 查询 table

Mysql transpose complex sql query table dynamically

我有一个包含两列的 table,架构如下:

create table scan( `application_name` varchar(255) NOT NULL, `defect_type` varchar(255) NOT NULL);

并相应地填充数据。 table 存储 "Application" 及其对应的 "Defect Type" 的数据。我想对此 table 执行以下 2 个操作:

  1. 获取特定应用程序的前 3 "Defect Type" 百分比。
  2. 转置上面的输出,其中 "Defect Type" (defect_type) 中的值成为列,其对应的百分比 (finalPercent) 作为其值。

我能做到1,下面是SQL Fiddle:

SQLFiddle

但是,我无法按照要求转置输出。理想情况下,在 1 和 2 之后应该有如下一行:

application_name | CrossSide |  CSS  |  XML 
       A         |   33.33   | 33.33 | 16.67 

谢谢!

您可以使用 group_concat 构建动态数据透视查询,然后执行它:

set @sql = null;

set @total = (select count(*) as totalcount from scan where application_name = "a");

select group_concat(distinct
    concat(
      'round(((count(case when defect_type = ''',
      defect_type,
      ''' then application_name end)/ @total ) * 100 ), 2) as `',
      defect_type, '`'
    )
  ) into @sql 
from ( select  defect_type 
        from   scan 
        where  application_name = "a" 
        group  by defect_type
        order by count(defect_type) desc
        limit 3) t;

set @sql = concat(
'select application_name, ', @sql,
' from scan
where application_name = "a" 
group by application_name'
);

prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;

SQLFiddle