今天遇到了一個以前沒有遇到過的問題,我把它歸類到“模糊分組統計”。
[題目]
若數據庫中數據表如下,根據type1分組求和,其中a,b項分解並分計算到a和b的結果中,得出第二個圖的結果。
---------從醬紫--------->>> ----------得出醬紫結果-------->>
這種統計,看着好簡單,但是沒有遇到過的時候是需要花很多時間去試錯。
最初呢,我的統計思路是如果有模糊的分組計算公式,那麼就萬事大吉了唄,所以花了些時間找對應的公式函數,但是沒有結果。
第二次,想着先剔除帶“,”的這種數據,只統計正常的數據,然後將非常規數據根據相似性(like%%)用left join 關聯一下但是on的時候發現“然無用”,關聯啥呢?
第三次,這個數據看來看去覺得還是需要增加輔助,將‘a,b'類型的數據分別添加到具有相似性的a或b後面,將a與a,b/b與a,b的數據結果相加,得出新的只有a/b的數據表,分組求和就行了。這個過程中,如何把'a,b'拆解開,想了很多公式:substring,min,locate,都是些獲取子串的函數、匹配子串開始位置的函數。最後只用上了if、locate。
鏘鏘~我的答案
[答案]
create table temp_data (type1 varchar(25),type2 int(11));
insert into temp_data values('a,b','1'),('a','2'),('b','3');
-------基礎數據合成,生成目標統計字段
create table temp_new as
select t.type1,t.num,t2.type1 as 'type2',t2.num2,if(locate(t.type1, t2.type1) > 0,t.type1,t2.type1) as 'type_new',if(locate(t.type1, t2.type1) > 0,t.num + t2.num2,t.num) as'num_new'from
(select from type1,type2 as 'num' from temp_data where type1 not like '%,%') t,
(select type1,type2 as 'num2' from temp_data where type1 like '%,%') t2;
--------最終求和結果
select type_new,sum(num_new) from temp_new group by type_new;
---------每天進步一點點------------