MYSQL,對同一個表進行多次COUNT的SQL


交集

  1. 通過子查詢,把多個COUNT的值放到同一個表中
  2. 在COUNT函數中,通過 id 去重,使得關聯表時去除了多余的數據
SELECT t1.allocationDate,COUNT1 as "分配客戶數",COUNT2 as "出方案客戶數",ROUND(COUNT2 / COUNT1,2) as "方案轉化率",COUNT3 as "成交客戶數",ROUND(COUNT3 / COUNT2,2) as "交易轉化率" 
FROM
(SELECT DATE_FORMAT(ar.allocationTime,"%Y-%m-%d") allocationDate,count(*) COUNT1 FROM appointment_record ar WHERE visible = 1
	and allocationTime >= @allocationStartTime 
	and allocationTime < @allocationEndTime GROUP BY allocationDate) t1,

	(SELECT DATE_FORMAT(ar.allocationTime,"%Y-%m-%d") allocationDate,count(DISTINCT ar.id) COUNT2 FROM appointment_record ar
	JOIN insurance_plan ip on ar.userId = ip.userId
	WHERE visible = 1
	and allocationTime >= @allocationStartTime 
	and allocationTime < @allocationEndTime GROUP BY allocationDate
	) t2 ,

	( SELECT DATE_FORMAT(ar.allocationTime,"%Y-%m-%d") allocationDate,count(*) COUNT3 FROM appointment_record ar WHERE ar.validOrders > 0 and visible = 1
	and allocationTime >= @allocationStartTime 
	and allocationTime < @allocationEndTime GROUP BY allocationDate ) t3

	WHERE t2.allocationDate = t1.allocationDate and t2.allocationDate = t3.allocationDate;

不斷疊加

非交集,可不斷疊加

SELECT t1.paymentDate,sum1 as "凈增標保", t2.count1 as "公司分配", t3.count2 as "自有客戶",t4.count3 as "客戶轉介紹",t5.count4 as "其他" from 
(SELECT DATE_FORMAT(io.paymentTime,"%Y-%m-%d") paymentDate,SUM(standardPremium) sum1 FROM insurance_order io WHERE io.visible = 1  GROUP BY paymentDate ) t1 
LEFT JOIN 
(SELECT DATE_FORMAT(io.paymentTime,"%Y-%m-%d") paymentDate,count(0) count1 FROM insurance_order io 
LEFT JOIN user_info ui on io.userId = ui.id LEFT JOIN channel cl on cl.id = ui.channel
WHERE io.visible = 1 and cl.channelTypeId = 1 GROUP BY paymentDate) t2 
on t1.paymentDate = t2.paymentDate 
LEFT JOIN 
(SELECT DATE_FORMAT(io.paymentTime,"%Y-%m-%d") paymentDate,count(0) count2 FROM insurance_order io 
LEFT JOIN user_info ui on io.userId = ui.id
LEFT JOIN channel cl on cl.id = ui.channel
WHERE io.visible = 1 and cl.channelTypeId = 2 GROUP BY paymentDate) t3
on t1.paymentDate = t3.paymentDate 
LEFT JOIN 
(SELECT DATE_FORMAT(io.paymentTime,"%Y-%m-%d") paymentDate,count(0) count3 FROM insurance_order io 
LEFT JOIN user_info ui on io.userId = ui.id
LEFT JOIN channel cl on cl.id = ui.channel
WHERE io.visible = 1 and cl.channelTypeId = 3 GROUP BY paymentDate) t4
on t1.paymentDate = t4.paymentDate 
LEFT JOIN 
(SELECT DATE_FORMAT(io.paymentTime,"%Y-%m-%d") paymentDate,count(0) count4 FROM insurance_order io 
LEFT JOIN user_info ui on io.userId = ui.id
LEFT JOIN channel cl on cl.id = ui.channel
WHERE io.visible = 1 and cl.channelTypeId = 99 GROUP BY paymentDate) t5
on t1.paymentDate = t5.paymentDate ;


免責聲明!

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



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