简体   繁体   English

在MySQL中旋转

[英]Pivoting in MySQL

I have a table in MySql tbl_Analysis with following structure 我在MySql tbl_Analysis有一个具有以下结构的表

uid | device_type
 1      Desktop
 2      Desktop
 3      Mobile
 4      Mobile
 5      Laptop
 6      Desktop

Now i need to get no. 现在我需要得到没有。 of users count group by device_type 用户数按device_type分组

I write the following query for this 我为此编写以下查询

select count(device_type) as count, 
device_type as device 
from tbl_Analysis 
group by device_type;

Following is result 以下是结果

count | device
 3       Desktop
 2       Mobile
 1       Laptop

Now I want these result to be pivot . 现在,我希望这些结果为pivot In Ms-Sql there is built in functionality available but I could not find any way of doing this in MySQL. Ms-Sql有内置的可用功能,但是我找不到在MySQL中执行此操作的任何方法。

My desired result is: 我想要的结果是:

Desktop | Mobile | Laptop
3          2        1

You can use a case expression to generate the pivot view. 您可以使用case表达式来生成数据透视图。

Query 询问

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小提琴

Another way to achieve this by dynamic sql. 通过动态sql实现此目的的另一种方法。

Query 询问

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 SQL小提琴

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

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