我有3个表:Users,Tools,tool_assigned:
用户:
ID | 名称 | 部门 |
---|---|---|
1个 | 约翰 | 一种 |
2 | 彼得 | b |
3 | 保罗 | 一种 |
工具:
ID | 名称 |
---|---|
1个 | 工具1 |
2 | 工具2 |
3 | 工具3 |
Tool_assigned:
ID | id_user | id_tool | 数量 |
---|---|---|---|
1个 | 1个 | 1个 | 1个 |
2 | 1个 | 2 | 3 |
3 | 1个 | 3 | 1个 |
4 | 2 | 1个 | 2 |
5 | 2 | 2 | 3 |
6 | 2 | 3 | 1个 |
7 | 3 | 1个 | 2 |
8 | 3 | 2 | 1个 |
9 | 3 | 3 | 1个 |
我需要得到以下结果:
id_tool | 工具名称 | 总量 | summary_department |
---|---|---|---|
1个 | 工具1 | 5 | a-1,b-2,c-2 |
2 | 工具2 | 7 | a-3,b-3,c-1 |
3 | 工具3 | 3 | a-1,b-1,c-1 |
我已经尝试过执行可以得到该结果的查询,但是到目前为止,我得到的最好的结果是:
SELECT tool.id, tool.name, sum(tool_assigned.quantity) as total_quantity,
group_concat(user.deparment, '-', tool_asigned.quantity) as summary_department
FROM tool_assigned
INNER JOIN users ON tool_assigned.id_user = user.id
INNER JOIN tools ON tool_assigned.id_tool = tool.id
GROUP BY tools.name, users.department
请帮助我,我已经尝试了一切。
您需要两个聚合级别:首先按工具和部门分类,然后仅按工具分类。您可以将其表达为:
select t.id, t.name as tool_name,
sum(x.quantity) as total_quantity,
group_concat(x.info order by x.department) as summary_department
from tools t
inner join (
select ta.id_tool, u.department, concat(u.name, '-', sum(t.quantity)) as info
from tool_assigned ta
inner join users on ta.id_user = u.id
group by ta.id_tool, u.department
) x on x.id_tool = t.id
group by t.id
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句