Mysql动态转置复杂的sql查询表

时间:2015-06-27 00:45:46

标签: mysql sql pivot transpose

我有一个包含两列的表,以下是架构:

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

并且相应地填充数据。该表存储“应用程序”及其相应的“缺陷类型”的数据。我想在此表上执行以下2个操作:

  1. 以百分比的形式获得特定应用程序的前三名“缺陷类型”。
  2. 转置上面的输出,其中“缺陷类型”(defect_type)中的值成为列,并将其对应的百分比(finalPercent)作为其值。
  3. 我能够实现1,以下是SQL小提琴:

    SQLFiddle

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

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

    谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用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