Mysql行列轉換


Table pivot行翻轉

2019年6月6日
9:16

標准化的數據庫是非常強大的,在數據庫的開發中,開發者需要竭盡所能的完善的數據保存的方法,同時保證讀寫的速度,最終一般通過三泛式來解決大多數問題,有時候我們需要信息以行的方法表現但是其分布在多個列中,這是我們就需要使用行翻轉來解決問題了;

假設數據庫存在以下三個表

Users
Items
User_Items

User_Items是用戶以物品之間的一個多對多的關系,為了簡單起見,我們不通過唯一的id來進行關連,而是人名與物品名稱進行關聯,第四個字段代表物品的價格;

 


假設如果需要統計每個人所持有的單個物品的價格,類似下圖

 

那么表中的數據需要經過一番加工才能以這種形式表現,我們一般可以通過編程語言比如java或php來實現,或者直接通過sql來完成;
通過sql實現行翻轉需要四步
1.選擇需要的列
2.通過選擇的列對表進行擴展
3.將表進行聚合
4.美化
步驟一:選擇需要的列
在此例子中我們需要找出item_type中的字段作為列的名稱
Item_amount作為行的值
步驟二:通過選擇的列對表進行擴展
create view User_Items_Extended as (
select
User_Items.Cust_Names,
case when Item_Type = "Computer" then Item_Amount end as Computer,
case when Item_Type = "Monitor" then Item_Amount end as Monitor,
case when Item_Type = "Software" then Item_Amount end as Software
from User_Items
);

通過以上步驟我們創建了一個表的視圖;

步驟三:將表進行聚合
create view User_Items_Extended_Pivot as (
select
Cust_Names,
sum(Computer) as Computer,
sum(Monitor) as Monitor,
sum(Software) as Software
from User_Items_Extended
group by Cust_Names
);

通過聚合函數group我們實現了每個user都有對應的行
步驟四:美化

create view User_Items_Extended_Pivot_Pretty as (
select
Cust_Names,
coalesce(Computer, 0) as Computer,
coalesce(Monitor, 0) as Monitor,
coalesce(Software, 0) as Software
from User_Items_Extended_Pivot
);

原文地址:http://stratosprovatopoulos.com/web-development/mysql/pivot-a-table-in-mysql/
相關文章:
1.https://stackoverflow.com/questions/22782932/mysql-get-first-non-null-value-after-group-by/22783112#22783112
2.https://stackoverflow.com/questions/1241178/mysql-rows-to-columns/9668036#9668036
3.Pivot table with dynamic columns in MySQL:http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM