我有一个包含两列的表,以下是架构:
create table scan( `application_name` varchar(255) NOT NULL, `defect_type` varchar(255) NOT NULL);
并且相应地填充数据。该表存储“应用程序”及其相应的“缺陷类型”的数据。我想在此表上执行以下2个操作:
我能够实现1,以下是SQL小提琴:
但是,我无法根据要求转置输出。理想情况下,在1和1之后应该有如下一行。 2在一起:
application_name | CrossSide | CSS | XML
A | 33.33 | 33.33 | 16.67
谢谢!
答案 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;