id

问题描述 投票:-4回答:1

如何编写一个查询,以获得以下的输出(见表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 |
+------+-------+
  • 用户 "a"、"b"、"c"、"d "属于类型1的 "cityA"。
  • 用户 "b"、"e"、"f "属于类型2的 "cityB"。

  • 用户 "c"、"d "属于经理 "a"。

  • 用户 "c"、"d"、"e"、"f "属于经理 "b"。

对所需的输出进行解释。

  1. 用户 "a "得到的总和是 "c "和 "d "的总和30,因为 "c "和 "d "都属于用户 "a "经理的范围
  2. 用户 "b "得到的总和是100,也就是 "c"、"d"、"e "和 "f "的总和,因为所有的用户都属于用户 "b "的管理者。
  3. 用户 "c "和 "d "得到的是自己的工资总额10和20,属于 "类型1 "的 "cityA"。
  4. 用户 "e "和 "f "得到的总和是70,70是属于 "cityB "的员工工资的总和,如果是 "类型2 "的话。
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
mysql sql join inner-join
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.