我們要做一張報表表格,從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 來判斷,不能用=或者!=來判斷