mysql 一對(duì)多 怎么在從表上面進(jìn)行多條件多次統(tǒng)計(jì)
問(wèn)題描述
主表 用戶表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)計(jì)每個(gè)人的電話情況(列表limit 0,10) 呼入幾次呼出幾次本地號(hào)碼幾次外地號(hào)碼幾次總呼入時(shí)間多少總呼出時(shí)間多少匹配公司多少(主要是這個(gè),因?yàn)槁?lián)系人表的phone有相同的,但對(duì)應(yīng)不同公司,left join sum()數(shù)據(jù)不準(zhǔn)確)匹配公司通話時(shí)間多少.......
主要問(wèn)題是:聯(lián)系人表的phone不唯一,有重復(fù)手機(jī)號(hào),例如一個(gè)人在兩家公司任職leftjoin 之后 sum 公司會(huì)有重復(fù)數(shù)據(jù),數(shù)據(jù)不準(zhǔn)確
其實(shí)我想過(guò)聯(lián)系人表phone去重之后在 跟別的表join,但是這樣速度會(huì)變得巨慢,要50s聯(lián)系人的表是5w以上的
好像這個(gè)是不能一條sql解決的
最終結(jié)果類似變成id name phone in_num(呼入次數(shù)) out_num(呼出次數(shù)) local_phone_num(本地號(hào)碼) .......23 ’小白’ 15523232323 45 120 30 .....24 ’小紅’ 18823232323 70 93 41 ......
問(wèn)題解答
回答1:首先你需要有個(gè)定義本地外地號(hào)碼的字段,然后是否需要展示沒(méi)有通話記錄的號(hào)碼,需要的話下面的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表的通話時(shí)間如果不是統(tǒng)計(jì)的int型分鐘數(shù)的話,可能你還需要轉(zhuǎn)換一下
回答2:執(zhí)行以下SQL,將會(huì)得到如下結(jié)果: (你問(wèn)題中期望的結(jié)果有點(diǎn)看不懂)
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)文章:
1. boot2docker無(wú)法啟動(dòng)2. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””3. docker-compose中volumes的問(wèn)題4. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.5. nignx - docker內(nèi)nginx 80端口被占用6. java - SSH框架中寫分頁(yè)時(shí)service層中不能注入分頁(yè)類7. javascript - mock.js可以存儲(chǔ)數(shù)據(jù)嗎8. docker api 開(kāi)發(fā)的端口怎么獲取?9. docker images顯示的鏡像過(guò)多,狗眼被亮瞎了,怎么辦?10. golang - 用IDE看docker源碼時(shí)的小問(wèn)題

網(wǎng)公網(wǎng)安備