我在 MySql tbl_Analysis
中有一个表格,其结构如下
uid | device_type
1 Desktop
2 Desktop
3 Mobile
4 Mobile
5 Laptop
6 Desktop
现在我需要得到否定。用户按device_type
我为此编写了以下查询
select count(device_type) as count,
device_type as device
from tbl_Analysis
group by device_type;
以下是结果
count | device
3 Desktop
2 Mobile
1 Laptop
现在我希望这些结果为pivot
。在Ms-Sql
中有内置的功能,但我无法在MySQL中找到任何方法。
我想要的结果是:
Desktop | Mobile | Laptop
3 2 1
答案 0 :(得分:1)
您可以使用case
表达式生成数据透视视图。
<强>查询强>
select
count(case when device_type = 'Desktop' then device_type end) as Desktop,
count(case when device_type = 'Mobile' then device_type end) as Mobile,
count(case when device_type = 'Laptop' then device_type end) as Laptop
from tb_analysis;
通过动态sql实现此目的的另一种方法。
<强>查询强>
set @query = null;
select
group_concat(distinct
concat(
'count(case when device_type = ''',
device_type, ''' then device_type end) as ' ,device_type
)
) into @query
from tb_analysis ;
set @query = concat('select ', @query, ' from tb_analysis
');
prepare stmt from @query;
execute stmt;
deallocate prepare stmt;