mysql-二維矩陣表格sql實現


背景

1、分兩個維度,統計數據並形成一個二維數據展現形式

2、橫軸標為統計維度1,縱軸為統計維度2

橫軸x區分為:x<=5,5<x<10,x>10
縱軸y區分為:y<=5,5<y<10,y>10

形成如下圖表格數據

  

維度2-->維度1 x<=5 5<x<10 x>10
y<=5 20 3 1
5<x<=10 1 2 1
y>10 0 0 1

步驟一:先統計出單筆兩個維度的值

select user,x,y from test01

  

 

如圖

user x y
A 1 2
B 6 2
C 5 10
D 7 11
E 11 2

步驟二:維度划分打標記

將每條記錄的x,y划入到對應分級中,例如:
記錄:A,x=1,y=2 划入等級為 A (x<=5) (y<=5)
記錄:B,x=6,y=2 划入等級為 A (5<x<=10) (y<=5)

  

select user 
user,
(case 
	when x<=5 then 'x<=5' 
	when x>5 and x<=10 then '5<x<=10' 
	when x>10 then 'x>10'
	else 'NULL' end) as tagX,
(case 
	when y<=5 then 'y<=5' 
	when y>5 and y<=10 then '5<y<=10' 
	when y>10 then 'y>10'
	else 'NULL' end) as tagY
from test01 

  

結果如圖:

user tagX tagY
A x<=5 y<=5
B 5<x<=10 y<=5
C x<=5 5<y<=10
D 5<x<=10 y>10
E x>10 y<=5

步驟三:取維度1,維度2組合-group by的結果

SQL如下

select tagX,tagY,count(1) as cnt from (
  步驟二sql
)t
group by tagX,tagY

  

 

即:

select tagX,tagY,count(1) as cnt from (
    select user 
    user,
    (case 
    	when x<=5 then 'x<=5' 
    	when x>5 and x<=10 then '5<x<=10' 
    	when x>10 then 'x>10'
    	else 'NULL' end) as tagX,
    (case 
    	when y<=5 then 'y<=5' 
    	when y>5 and y<=10 then '5<y<=10' 
    	when y>10 then 'y>10'
    	else 'NULL' end) as tagY
    from test01 
)t
group by tagX,tagY

  

 

結果如圖:

tagX tagY cnt
5<x<=10 y<=5 1
5<x<=10 y>10 1
x<=5 5<y<=10 1
x<=5 y<=5 1
x>10 y<=5 1

步驟四:將tagX轉成橫軸,tagY轉成縱軸

橫軸:x<=5,5<x<=10,x>10 
(由於縱軸需要占用一個空間所以需要虛擬一個頂級橫軸)
---> (y/x)|x<=5|5<x<=10|x>10 

縱軸:y<=5,5<y<=10,y>10

需要將tagY group by tagX通過case when 橫向平鋪

  

 

SQL如下:

select 
tagY as 'y/x', 
sum(case when tagX ='x<=5' then cnt else 0 end) as 'x<=5',
sum(case when tagX ='5<x<=10' then cnt else 0 end) as '5<x<=10',
sum(case when tagX ='x>10' then cnt else 0 end) as 'x>10'
from(
	步驟三sql
)m
group by tagY

  

 

即:

select 
tagY as 'y/x', 
sum(case when tagX ='x<=5' then cnt else 0 end) as 'x<=5',
sum(case when tagX ='5<x<=10' then cnt else 0 end) as '5<x<=10',
sum(case when tagX ='x>10' then cnt else 0 end) as 'x>10'
from(
	select tagX,tagY,count(1) as cnt from (
		select user 
		user,
		(case 
			when x<=5 then 'x<=5' 
			when x>5 and x<=10 then '5<x<=10' 
			when x>10 then 'x>10'
			else 'NULL' end) as tagX,
		(case 
			when y<=5 then 'y<=5' 
			when y>5 and y<=10 then '5<y<=10' 
			when y>10 then 'y>10'
			else 'NULL' end) as tagY
		from test01 
	)t
  group by tagX,tagY
)m
group by tagY

 

得最終結果如圖:


免責聲明!

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



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