簡體   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