在MySQL中进行透视

时间:2015-10-01 05:52:10

标签: mysql pivot-table

我在 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

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 Fiddle

通过动态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;

SQL Fiddle