[英]How to group customers into 4 ranks using MYSQL query
我們存儲客戶數據,例如他們在下達的不同訂單上花費的姓名,userId和總金額,現在我想根據到目前為止的總金額將客戶分組為1至4級。 下面是我正在使用的腳本,但是需要花費很多時間,有沒有更好的方法呢? 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;
}
謝謝!
為了提高速度,您可以在dateCreate
列上創建索引,並使用以下條件使MySQL使用它:
WHERE ORD.dateCreate >= '2013-01-01'
就分組而言,您可以使用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.