【发布时间】:2020-09-08 16:34:33
【问题描述】:
如何编写查询以获得以下输出(见表 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”
所需输出的解释:
- 用户“a”得到总数 30,即“c”和“d”之和,因为“c”和“d”都属于用户“a”经理
- 用户“b”得到总数 100,即“c”、“d”、“e”和“f”的总和,因为所有用户都属于用户“b”经理
- 用户“c”和“d”得到总和10和20,这是他们自己的工资,属于“类型1”的“cityA”
- 用户“e”和“f”得到总数70和70,即员工工资的总和属于“城市B”,如果属于“类型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
【问题讨论】:
-
到目前为止,您是否尝试过任何方法来解决问题。如果
yes,请告诉我们。我认为答案不应该是no。 -
我确实在 user_city_mapping 上进行了自我加入,对于城市“类型 2”的经理和员工来说,我得到了很好的输出,因为不知道如何处理城市“类型 1”的员工—— - 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
-
将查询放在问题中,而不是评论中,这样您就可以将其格式化为可读。
-
您应该使用
@符号来限定此人的姓名,例如@Barmar。我投票决定重新开放,但需要更多投票。 -
@AnilkumarBind 我自己无法重新打开问题,但我添加了我的投票
标签: mysql sql join inner-join