我正在尝试制作一个报告,在这里我需要知道另一个表中的项目计数
+----------+--------+--------------------------------------------+
| Sale No. | Widget | Total Sold |
+----------+--------+--------------------------------------------+
| 123 | foo | Dcount(another table where widget = "foo") |
| 456 | bar | Dcount(another table where widget = "bar") |
+----------+--------+--------------------------------------------+
。
SELECT [Sale No.]
, Widget
, Dcount("SELECT foo from whatever where widget = " & widget) as [Total Sold]
FROM sometable
不幸的是,这会查询数据库中的每条记录,因为这样的报告必须每天运行,所以效率不高。
是否有一种方法可以查询一次,可以通过VBA或某些我不知道将查询保留在内存中的SQL还是每个唯一项的计数。基本上只查询一次而不是N次。
这是一个更准确的表格,可以更准确地反映我的数据
+----------+------------+---------+------------------+
| Employee | Department | Policy | Review Requested |
+----------+------------+---------+------------------+
| 123 | Sales | PlanABC | TRUE |
| 456 | Sales | PlanABC | TRUE |
| 789 | Accounting | PlanXYZ | FALSE |
| 101112 | Accounting | PlanXYZ | TRUE |
| 131415 | Sales | PlanXYZ | FALSE |
| 161718 | Admin | PlanJKL | TRUE |
+----------+------------+---------+------------------+
我想要的结果
+------------+----------+---------+----------------------+
| Department | Employee | Policy | Count of All Polices |
+------------+----------+---------+----------------------+
| Sales | 123 | PlanABC | 2 |
| Sales | 456 | PlanABC | 2 |
| Accounting | 101112 | PlanXYZ | 3 |
| Admin | 161718 | PlanJKL | 1 |
+------------+----------+---------+----------------------+
答案 0 :(得分:0)
如果您的表格设置如下:
| Sale No | Widget |
|---------|--------|
| 1 | Foo |
| 2 | Bar |
| 3 | Foo |
| 4 | Foo |
| 5 | Bar |
| 6 | Foo |
| 7 | Foo |
| 8 | Bar |
| 9 | Bar |
| 10 | Foo |
您不能包含Sale No
,因为它将对其中的值进行分组。
SELECT Widget
, COUNT(Widget) AS [Total Sold]
FROM sometable
GROUP BY Widget
仅添加小部件并对其进行分组将返回:
| Widget | Total Sold |
|--------|------------|
| Bar | 4 |
| Foo | 6 |
另一方面,如果您的Sale No
字段是重复的,那么您可以获得每个Sale No
的计数。
| Sale No | Widget |
|---------|--------|
| 1 | Foo |
| 1 | Bar |
| 5 | Foo |
| 5 | Foo |
| 5 | Bar |
| 7 | Foo |
| 7 | Foo |
| 7 | Bar |
| 7 | Bar |
| 10 | Foo |
在此处添加Sale No
并将查询按未聚合的所有字段分组。
SELECT [Sale No]
, Widget
, COUNT(Widget) As [Total Sold]
FROM sometable
GROUP BY [Sale No]
, Widget
这将返回此表:
| Sale No | Widget | Total Sold |
|---------|--------|------------|
| 1 | Bar | 1 |
| 1 | Foo | 1 |
| 5 | Bar | 1 |
| 5 | Foo | 2 |
| 7 | Bar | 2 |
| 7 | Foo | 2 |
| 10 | Foo | 1 |
修改:
根据提供的表,此SQL应给出正确的结果:
SELECT T1.Department
, T1.Employee
, T1.Policy
, COUNT(T2.Policy)
FROM sometable T1 INNER JOIN sometable T2 ON T1.Policy = T2.Policy
GROUP BY T1.Department
, T1.Employee
, T1.Policy
结果表:
| Department | Employee | Policy | Expr1003 |
|------------|----------|---------|----------|
| Accounting | 789 | PlanXYZ | 3 |
| Accounting | 101112 | PLanXYZ | 3 |
| Admin | 161718 | PLanJKL | 1 |
| Sales | 123 | PlanABC | 1 |
| Sales | 456 | PalnABC | 1 |
| Sales | 131415 | PlanXYZ | 3 |