1. 定義
sql
城市等級(city_rank)小於3且GMV大於6000或者城市等級大與3且GMV大於5000定義爲高消費(gq)ide
城市等級(city_rank)小於3且廣告收入大於360或者城市等級大與3且廣告收入大於300定義爲高收入(pq)ci
flow_rank: 0低流量 1中流量 2高流量
it
合做商跨多個城市,選擇city_rank最小值爲其city_rank,毛收入多城市取和,廣告毛收入按合做商收取table
2. 要求查詢class
GMV城市最高小於10000、總和小於30000、非首次合做、如GMV有量毛利大於0.02test
高消費額、低收入、非高流量;低消費額、高收入、非高流量;低消費額、低收入、中流量;低消費額、低收入、低流量,且合做商gmv超過2000select
3. 實現
總結
select distinct tc.partner_id as partnerId, tc.contract_id as contractId, tc.contract_num as contractNum, tc.bd_id as bdId, tc.org_id as orgId, if(tc.org_scale='NULL','0',tc.org_scale) as orgScale from table tc join ( select tc.partner_id, case when min(city_rank)<=3 and avg(t.gmv)>=6000 then 1 when min(city_rank)>3 and avg(t.gmv)>=5000 then 1 else 0 end as gq, case when min(city_rank)<=3 and avg(t.gross_profit+t.advertisement_gross_profit)>=360 then 1 when min(city_rank)>3 and avg(t.gross_profit+t.advertisement_gross_profit)>=300 then 1 else 0 end as pq, max(tc.flow_rank) as fq, sum(t.gmv) as gmv from ( select partner_id,poi_id,min(city_rank) as city_rank, max(tc.flow_rank) as flow_rank, sum(is_old) as is_old from table tc where tc.partner_id>=#{start} and tc.partner_id<=#{end} group by partner_id,poi_id ) tc join ( select poi_id, sum(gmv) as gmv, sum(gross_profit) as gross_profit, avg(advertisement_gross_profit) as advertisement_gross_profit from table tc where tc.partner_id>=#{start} and tc.partner_id<=#{end} group by poi_id ) t on tc.poi_id=t.poi_id group by tc.partner_id having max(t.gmv)<10000 and sum(t.gmv)<30000 and sum(tc.is_old)>0 and case when sum(gmv)>0 then sum(gross_profit)/sum(gmv)>0.02 else 1=1 end ) t2 on t.partner_id=tc.partner_id where ]]> <if test="type ==0"> ((t2.gq=1 and t2.pq=0 and fq!=2) or (t2.gq=0 and t2.pq=1 and fq!=2) or (t2.gq=0 and t2.pq=0 and fq=1) or (t2.gq=0 and t2.pq=0 and fq=0 and t2.gmv>2000)) </if>
4. 關鍵查詢
4.1 t2
a) tc子查詢計算流量、是否首次合做
b) t子查詢計算毛利、毛收入
c) 計算合做商消費額、流量、收入類型,查詢知足要求1的合做商
d) having子查詢過濾,case子句限制毛利率
4.2 要求2
where過濾
5. 總結
大量使用了聚合計算、過濾,業務功能使用一條SQL實現
若是用代碼實現相似的功能,複雜程度能夠想象,每一個聚合都會對應一大坨代碼