我有一个数据库设置,它可以保存已经收集了一定金额的销售人员的数据,并在那里也有佣金。
Example:
Date Name Amount Sold Commission Earned
2013-2-3 John A 100.00 20.00
2013-2-3 Amy W 200.00 40.00
2013-2-3 John A 230.00 46.00
2013-2-2 John A 300.00 60.00
2013-2-2 Bill B 400.00 80.00
Etc....
我试图通过整周赢得的佣金来展示最畅销的销售人员。我需要以某种方式查询数据库以查找本周的所有佣金,然后将它们分组并汇总所获得的总数并显示本周的最高收入者。
这是我到目前为止所做的工作,但它显示了上周所有收入。我只是不知道如何按照他们的名字对它们进行分组,然后将佣金加在一起,然后从最赚钱的销售人员那里展示。
require_once('connectvars.php');
$dbc = mysqli_connect(CDB_HOST, CDB_USER, CDB_PASSWORD, CDB_NAME);
// GET COLLECTOR INFO
$query = "SELECT * FROM commissioninfo WHERE thedate >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND thedate < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY ORDER BY amountoffeeearned DESC";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $row['salesperson'] . '</td>';
echo ' <td>' . $row['amountoffeeearned'] . '</td>';
echo '</tr>';
}
mysqli_close($dbc);
答案 0 :(得分:2)
只需在Name
中添加Group by
,然后Sum
Amount Sold
,您将获得Amount Sold
每user
的总和。这样的事情。
SELECT NAME,
Sum(`Amount Sold`) sum_amount ,
sum(`commission earned`) sum_comm
FROM commissioninfo
WHERE thedate >= curdate() - interval dayofweek(curdate())+6 day
AND thedate < curdate() - interval dayofweek(curdate())-1 day
GROUP BY NAME
ORDER BY sum_amount DESC
更新:
SELECT salesperson,
Sum(amountcollected)
FROM commissioninfo
WHERE thedate >= Curdate() - INTERVAL Dayofweek(Curdate())+6 day
AND thedate < Curdate() - INTERVAL Dayofweek(Curdate())-1 day
GROUP BY salesperson
答案 1 :(得分:0)
按顺序在DESC中添加分组依据和SUM([佣金获得])中的名称。
或强>
试试这个:
SELECT Name,
SUM([Amount Sold]) as WeekAmountSold,
SUM([Commission Earned]) as WeekCommissionEarned
FROM commissioninfo
WHERE Date >= DATE_ADD(curdate(), INTERVAL(1-DAYOFWEEK(curdate())-7) DAY)
AND Date < DATE_ADD(curdate(), INTERVAL(1-DAYOFWEEK(curdate())) DAY)
GROUP BY Name
ORDER BY SUM([Commission Earned]) DESC