mysql 一對多 怎么在從表上面進(jìn)行多條件多次統(tǒng)計
問題描述
主表 用戶表id name phone (關(guān)聯(lián)字段)
從表 通話記錄表id phone(關(guān)聯(lián)字段) ot_phone time type (呼入呼出) input_time
聯(lián)系人表id c_id phone
公司表c_id name
怎么統(tǒng)計每個人的電話情況(列表limit 0,10) 呼入幾次呼出幾次本地號碼幾次外地號碼幾次總呼入時間多少總呼出時間多少匹配公司多少(主要是這個,因為聯(lián)系人表的phone有相同的,但對應(yīng)不同公司,left join sum()數(shù)據(jù)不準(zhǔn)確)匹配公司通話時間多少.......
主要問題是:聯(lián)系人表的phone不唯一,有重復(fù)手機(jī)號,例如一個人在兩家公司任職leftjoin 之后 sum 公司會有重復(fù)數(shù)據(jù),數(shù)據(jù)不準(zhǔn)確
其實我想過聯(lián)系人表phone去重之后在 跟別的表join,但是這樣速度會變得巨慢,要50s聯(lián)系人的表是5w以上的
好像這個是不能一條sql解決的
最終結(jié)果類似變成id name phone in_num(呼入次數(shù)) out_num(呼出次數(shù)) local_phone_num(本地號碼) .......23 ’小白’ 15523232323 45 120 30 .....24 ’小紅’ 18823232323 70 93 41 ......
問題解答
回答1:首先你需要有個定義本地外地號碼的字段,然后是否需要展示沒有通話記錄的號碼,需要的話下面的sql改成left join并且右表取值需要做一下判空處理,不需要的話就可以直接用了
select id,name,phone, sum(case when type=’in’ then 1 else 0 end) cnt_in, sum(case when type=’out’ then 1 else 0 end) cnt_out, sum(case when iflocal=’1’ then 1 else 0 end) cnt_local, sum(case when iflocal=’0’ then 1 else 0 end) cnt_nonlocal, sum(case when type=’in’ then input_time else 0 end) alltime_in, sum(case when type=’out’ then input_time else 0 end) alltime_out from userlist a join phonelist b on a.phone=b.phone group by a.phone;
補(bǔ)充一下,b表的通話時間如果不是統(tǒng)計的int型分鐘數(shù)的話,可能你還需要轉(zhuǎn)換一下
回答2:執(zhí)行以下SQL,將會得到如下結(jié)果: (你問題中期望的結(jié)果有點看不懂)
idnamephonetypecount23小白15523232323in1423小白15523232323out287SQL
SELECT a.id, a.name, b.phone, -- 坐席自己的電話 b.type, -- 呼入呼出 ’in’ or ’out’ b.count -- 次數(shù)FROM phoneList a LEFT JOIN (SELECT phone, type, count(1) AS count FROM phoneLog GROUP BY phone, type) b ON a.phone = b.phone回答3:
可以使用外連接查詢
相關(guān)文章:
