MYSQL 巧用count,sum進行統計數據


SELECT a.user,count(b.order_id) as subcount,sum(if(b.verifysta='Y',1,0)) as passcount FROM vicidial_users a LEFT JOIN vicidial_order b on a.user = b.user WHERE a.user_group = 'TeamOne' GROUP BY a.user;

sum(if(b.verifysta='Y',1,0))  

如果verifysta為Y,就加1,否則為0,

這個太棒了。

把邏輯放到sql中,會大大的減少程序的工作量,而且效率很高。

這樣既能獲取到全部的訂單提交,也能獲取審核通過的訂單提交。

select a.user,a.full_name,count(b.order_id) as subcount,sum(if(b.verifysta='Y',1,0)) as passcount from vicidial_users a LEFT JOIN (SELECT user,order_id,verifysta from vicidial_order where time>UNIX_TIMESTAMP('2015-11-7') and time<UNIX_TIMESTAMP('2015-11-7 23:59:59') and user_group = 'TeamOne')  b on a.user = b.user WHERE a.user_group = 'TeamOne' GROUP BY a.user;

根據日期篩選,先篩選出order數據(where條件都在其中),如果where放在外面的話,就會把數據過濾掉了。

拆分開來如下:

SELECT user,order_id,verifysta from vicidial_order where time>UNIX_TIMESTAMP('2015-11-7') and time<UNIX_TIMESTAMP('2015-11-7 23:59:59') and user_group = 'TeamOne';

根據條件,獲取所有的存在的數據。

 

select a.user,a.full_name,b.order_id,b.verifysta='Y' from vicidial_users a LEFT JOIN (SELECT user,order_id,verifysta from vicidial_order where time>UNIX_TIMESTAMP('2015-11-7') and time<UNIX_TIMESTAMP('2015-11-7 23:59:59') and user_group = 'TeamOne')  b on a.user = b.user WHERE a.user_group = 'TeamOne';

獲取全部的數據,不進行count、sum、group by 處理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM