如何编写一个查询,以获得以下的输出(见表4
table user : role - 1:manager, 2:employee
+----+------+-----------+--------+
| id | name | role | salary |
+----+------+-----------+--------+
| 1 | a | 1 | 0 |
| 2 | b | 1 | 0 |
| 3 | c | 2 | 10 |
| 4 | d | 2 | 20 |
| 5 | e | 2 | 30 |
| 6 | f | 2 | 40 |
+----+------+-----------+--------+
table city
+----+--------+------+
| id | name | type |
+----+--------+------+
| 1 | cityA | 1 |
| 2 | cityB | 2 |
+----+--------+------+
table user_city_mapping
+----+-----------+---------+
| id | user_id | city_id |
+----+-----------+---------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 2 | 2 |
| 4 | 3 | 1 |
| 5 | 4 | 1 |
| 6 | 5 | 2 |
| 7 | 6 | 2 |
+----+-----------+---------+
output required
+------+-------+
| name | total |
+------+-------+
| a | 30 |
| b | 100 |
| c | 10 |
| d | 20 |
| e | 70 |
| f | 70 |
+------+-------+
用户 "b"、"e"、"f "属于类型2的 "cityB"。
用户 "c"、"d "属于经理 "a"。
对所需的输出进行解释。
In short,
if an employee falls under any manager, the manager get the sum of the salary of the employee under him.
if the employee belongs to "type 1" city he gets his salary.
if an employee belongs to the "type 2" city he gets the sum of all employees belongs to that city.
以上提供的详情是需求和输出。我无法得到所需输出的查询。
我试过的东西
SELECT b.user_id, sum(salary)
FROM user_city_mapping a
INNER JOIN user_city_mapping b
ON a.city_id = b.city_id
INNER JOIN user
ON a.user_id = user.id AND role = 2
GROUP BY b.user_id