我必须从2个表中查询一些派生值。他们的简化结构如下:
用户有一个ID和一个父列,表示其父级的ID。每个用户还有一个佣金值,表示他们从他们的员工中获得的销售额百分比。
只有员工可以进行销售,并且该信息会记录在下表中
+------------------------------------+
| ID Name Parent Commission |
+------------------------------------+
| 1 SeniorManager NULL 5 |
| 2 Manager 1 10 |
| 3 Employee1 2 13 |
| 4 Employee2 2 12 |
+------------------------------------+
此表记录通过其ID链接的员工的销售额。它记录销售金额以及销售时间。
+---------------------------+
| user_id amount created_at |
+---------------------------+
| 3 100 2014-01-16 |
| 3 120 2014-01-16 |
| 3 110 2014-01-16 |
+---------------------------+
从系统的其他部分,我知道给定ID的用户的深度。在实际的系统中,有7个固定的级别,但为了这个问题我在这里进行了简化。
我想写的查询是:给定高级管理人员的ID和日期范围,显示他下面的经理列表,这些经理的汇总佣金以及该经理预期的佣金。因此,鉴于以上数据,人们会期望:
+--------------------------------------------+
| Name Sales ManagerCommission Commission |
+--------------------------------------------+
| Manager 330 33.30 16.65 |
+--------------------------------------------+
我到目前为止的查询是:
SELECT
users.name AS Name,
SUM(sales.amount) AS Sales,
SUM(sales.amount) * (users.commission/100) AS ManagerCommission
FROM
users
LEFT JOIN users AS employees
ON employees.parent = users.id
LEFT JOIN sales
ON sales.id = employees.id AND
sales.created_at BETWEEN DATE(?) AND DATE(?)
WHERE
users.parent = ?
GROUP BY
users.name
我不确定如何获得由经理而非员工分组的佣金的最后一列值。另外作为一个附带问题,有没有办法重用在select语句中使用两次的SUM(sales.amount)
。我宁愿不两次计算完全相同的值。我打算为每个已知的深度编写7个查询。有没有更有效的方法呢?
答案 0 :(得分:0)
为每个管理级别添加一个联接: -
SELECT
senior_manager.name AS Name,
SUM(sales.amount) AS Sales,
SUM(sales.amount * manager.commission/100) AS ManagerCommission,
SUM(sales.amount) * (senior_manager.commission/100) AS SeniorManagerCommission
FROM
users AS senior_manager
LEFT JOIN users AS manager
ON manager.parent = senior_manager.id
LEFT JOIN users AS employees
ON employees.parent = manager.id
LEFT JOIN sales
ON sales.id = employees.id AND
sales.created_at BETWEEN DATE(?) AND DATE(?)
WHERE
senior_manager.id = ?
GROUP BY
senior_manager.name
SQL小提琴: -