程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> MYSQL入門知識 >> MySQL 按照范圍/等級 進行Group By

MySQL 按照范圍/等級 進行Group By

編輯:MYSQL入門知識
 

我們要做一張報表表格,從mysql裡取出數據,然後按等級分組,如何實現呢?

MySQL 示例 SQL:

SELECT
ftime,
sum(cost) as cost,
count(advertiser_id) as aduser_num,
sum(pv) as pv,
sum(vc) as vc,
CASE
WHEN cost>100000 THEN ‘1’
WHEN cost>50000 and cost<=100000 THEN ‘2’
WHEN cost>10000 and cost<=50000 THEN ‘3’
WHEN cost>5000 and cost<=10000 THEN ‘4’
WHEN cost>1000 and cost<=5000 THEN ‘5’
WHEN cost>100 and cost<=1000 THEN ‘6’
ELSE ‘7’ END as cost_range
from (
SELECT
ftime,
advertiser_id,
sum(real_cash+vir_cash+gift_cash+divide_cash)/100 as cost,
sum(exposure_cnt) as pv,
sum(valid_click_cnt) as vc
from etail_day
where ftime in(20140603) group by ftime,advertiser_id
) as tmp_table
group by
ftime,CASE
WHEN cost>100000 THEN ‘1’
WHEN cost>50000 and cost<=100 THEN ‘2’
WHEN cost>10000 and cost<=50000 THEN ‘3’
WHEN cost>5000 and cost<=10000 THEN ‘4’
WHEN cost>1000 and cost<=5000 THEN ‘5’
WHEN cost>100 and cost<=1000 THEN ‘6’
ELSE ‘7’ END ;

利用SQL對某個表中的數據按照某個范圍進行等級劃分,並按照劃分後的等級 group by。實現思路見上:

(1)將該表的記錄取出,如果有函數運算的話,搞個虛擬字段表示
(2)將(1)中的查詢結果構建一張臨時表,然後弄一個臨時表別名:tmp_table
(3)從臨時表中取出數據,按范圍group by

可能會遇到的問題:

MySQL Error: Every derived table must have its own alias(這句話的意思是說每個派生出來的表都必須有一個自己的別名),那可能是別名不對,檢查下臨時表別名

可能會出現null的值,這時候


◦null和任何值都不能比較

 

◦null只能用is null 或者is not null 來判斷,不能用=或者!=來判斷

 

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved