繁体   English   中英

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

[英]Mysql transpose complex sql query table dynamically

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

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

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

  1. 以百分比的形式获得特定应用程序的前3个“缺陷类型”。
  2. 转置上面的输出,其中“缺陷类型”(defect_type)中的值成为列,其对应的百分比(finalPercent)作为其值。

我能够实现1,以下是SQL小提琴:

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

暂无
暂无

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

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