工做中用到統計12月份通話記錄,統計號碼撥打次數,可是問題出在一個號碼能夠撥打屢次,每次可能接通也可能不接通,若是用主叫號碼caller字段group by分組後count(*)統計數目,這樣會致使不能看到統計數目中幾條是接通,幾條是未接通的,因而想到用union分是否接通各自統計,而後將統計結果按照號碼排序放到一塊兒,具體實現以下mysql
billid(通話記錄id),caller(主叫號碼),callerstarttime(撥打時間),callerResult(撥打結果0未接通 1接通)sql
sql實現語句以下:spa
SELECT bill_id,Caller,from_unixtime(CallerStartTime,'%Y-%c-%d %h:%i:%s') as date,CallResult,count(*) as num FROM `sup_tel_record` where CallerStartTime > 1417363200 and CallerStartTime < 1420041600 and CallResult = 0 group by Caller union SELECT bill_id,Caller,from_unixtime(CallerStartTime,'%Y-%c-%d %h:%i:%s') as date,CallResult,count(*) as num FROM `sup_tel_record` where CallerStartTime > 1417363200 and CallerStartTime < 1420041600 and CallResult = 1 group by Caller order by date asc
輸出結果以下:unix
注意使用union進行sql語句鏈接時,第一條sql語句不能使用order by排序,不然會出現code
mysql錯誤 1221 Incorrect usage of union and order byblog