我使用的是 MS Access 2010。数据库有一组 12 个相同的设备表,每个表对应公司的 12 个不同部门。该表跟踪负责设备的人员(资源)需要采取的操作。我有一个简单的查询,可以计算具有各种状态的资源数量。它看起来如下:
SELECT dept1.actions.resource, dept1.action.status, Count(*) AS status_count
FROM dept1.action
GROUP BY dept1.action.status, dept1.action.resource;
每个表如下所示:
equip_id, text
resource, number (id of the resource who is responsible for the equipment)
status, number (id of the status of the action that the resource needs to do)
查询结果如下所示:
resource status status_count
1 1 63
2 1 79
5 1 16
6 1 3
0 3 1
1 3 1180
2 3 64
3 3 61
5 3 1
6 3 2
7 3 12
0 4 4
例如,第一行显示资源 1 有 63 件状态为 1 的设备。第二行显示资源 2 有 79 件状态为 1 的设备……以此类推。
我需要的是一个聚合查询,它提供所有资源和状态组合的公司级总计,即完全相同的结果表,只是 status_count 列的数字要大得多。
感谢您提供的任何帮助。
最佳答案
基本上,您可以选择数据库中每个 dep 表的计数,将它们全部合并然后求和。
SELECT resource,status,sum(status_count) as status_company_count from(
SELECT dept1.actions.resource, dept1.action.status, Count(*) AS status_count
FROM dept1.action
GROUP BY dept1.action.status, dept1.action.resource
UNION
SELECT dept2.actions.resource, dept2.action.status, Count(*) AS status_count
FROM dept2.action
GROUP BY dept2.action.status, dept2.action.resource
UNION
SELECT dept3.actions.resource, dept3.action.status, Count(*) AS status_count
FROM dept3.action
GROUP BY dept3.action.status, dept3.action.resource
.....)
group by resource,status;
关于sql - 跨多个表的聚合 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34836370/