[英]How to group customers into 4 ranks using MYSQL query
We store the customer data like name, userId and Total Amount they spent on different orders they place, now I want to group a customer into ranks 1 to 4 based on Total Amount he spent till now. 我们存储客户数据,例如他们在下达的不同订单上花费的姓名,userId和总金额,现在我想根据到目前为止的总金额将客户分组为1至4级。 Below is the script I am using but it takes a lot of time, is there any better way to do this??
下面是我正在使用的脚本,但是需要花费很多时间,有没有更好的方法呢? There is no index on dateCreate Field.
dateCreate字段上没有索引。
public function getBiggestSpenders($customerUserId){
global $db, $database;
$sql = "SELECT userId, SUM(total) AS Total, ORD.dateCreate
FROM $database.`order` ORD
WHERE year(ORD.dateCreate) >= '2013'
group by ORD.userId
order by Total DESC";
$result = $db->getTable($sql);
$numRows = count($result);
$flag=0;
for($i=0;$i<$numRows && $flag==0;$i++){
$userId = $result[$i]['userId'];
if($userId==$customerUserId){
$position = $i;
$Total = $result[$i]['Total'];
$flag=1;
}
}
$quartile = $this->getQuartiles($numRows, $position);
if($quartile==1)
return $quartile;
else
return 0;
}
public function getQuartiles($numRows, $position){
$total = $numRows;
$segment = round($total / 4);
$Quartile = floor($position / $segment) + 1;
return $Quartile;
}
Thanks! 谢谢!
To improve the speed, you can create an index on dateCreate
column and use the following condition to make MySQL use it: 为了提高速度,您可以在
dateCreate
列上创建索引,并使用以下条件使MySQL使用它:
WHERE ORD.dateCreate >= '2013-01-01'
As far as grouping is concerned, you can use CASE
statement to define groups based on spending, eg: 就分组而言,您可以使用
CASE
语句根据支出定义分组,例如:
SELECT userId, SUM(total) AS Total,
CASE
WHEN Total >= 2000 then 1
WHEN Total >= 1000 AND Total <2000 THEN 2
WHEN Total >=500 AND Total < 1000 THEN 3
ELSE 4
END as `rank`,
ORD.dateCreate
FROM $database.`order` ORD
WHERE ORD.dateCreate >= '2013-01-01'
group by ORD.userId
order by Total DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.