查询按月总销售额获得前5名用户

时间:2013-07-04 04:33:02

标签: mysql sql mysqli

我希望你能帮我解决这个问题。我想运行query来搜索表格及其所有行,日期与当前月份匹配。然后返回user_id。我想要实现的是收集此query下的前5个用户ID。

如何更改此选项以查找当月的前5名?我通常能够弄清楚我的疑问,但这个让我难过。

这就是我现在所拥有的一切。

$top = mysqli_query($mysqli, "SELECT sum(amount) AS total FROM sales WHERE status = 'S' AND MONTH(date) = 1");

    while($row = mysqli_fetch_row($top))
         {

           $userid = $row['0'];

         }

更新

$top = mysqli_query($mysqli, "SELECT user_id
    FROM
    (
        SELECT user_id, SUM(amount) total 
        FROM sales 
        WHERE status = 'S' 
        AND MONTH(date) = MONTH(CURDATE())
        AND YEAR(date)  =  YEAR(CURDATE())
        GROUP BY user_id
    ) q
        ORDER BY total DESC
        LIMIT 5");

           while($row = mysqli_fetch_row($top))
                {
                   $topsales[] = $row['0'];
                }

    foreach($topsales as $topsale) {
            echo $topsale;
    }

1 个答案:

答案 0 :(得分:1)

你在寻找这样的查询吗?

SELECT user_id
  FROM
(
  SELECT user_id, SUM(amount) total 
    FROM sales 
   WHERE status = 'S' 
     AND MONTH(date) = MONTH(CURDATE())
     AND YEAR(date)  =  YEAR(CURDATE())
  GROUP BY user_id
) q
 ORDER BY total DESC
 LIMIT 5

或只是

SELECT user_id 
  FROM sales 
 WHERE status = 'S' 
   AND MONTH(date) = MONTH(CURDATE())
   AND YEAR(date)  =  YEAR(CURDATE())
 GROUP BY user_id
 ORDER BY SUM(amount) DESC
 LIMIT 5

这是 SLQFiddle 演示

注意:使用MONTH()YEAR()函数会阻止MySql使用您在date列上可能拥有的任何索引


现在你的php代码可能看起来像这样

$db  = new mysqli('localhost', 'user', 'password', 'dbname');
if ($db->connect_errno) {
    die('Cannot connect'); // TODO: better error handling
}
$sql = "SELECT user_id 
          FROM sales 
         WHERE status = 'S' 
           AND MONTH(date) = MONTH(CURDATE())
           AND YEAR(date)  =  YEAR(CURDATE())
         GROUP BY user_id
         ORDER BY SUM(amount) DESC
         LIMIT 5";

$topsales = array();

if ($query = $db->prepare($sql)) {
    $query->execute();
    $query->bind_result($user_id);

    while ($query->fetch()) {
        $topsales[] = $user_id;
    }
    $query->close();
} else {
    die('Unable to prepare: ' . $db->error); // TODO: better error handling
}
$db->close();

foreach ($topsales as $topsale) {
    echo $topsale . '<br>';
}