简体   繁体   中英

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. 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.

    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:

WHERE ORD.dateCreate >= '2013-01-01'

As far as grouping is concerned, you can use CASE statement to define groups based on spending, eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM