繁体   English   中英

在MySQL中旋转

[英]Pivoting in MySQL

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

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

通过动态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小提琴

暂无
暂无

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

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