基于动态标准的多次计数

时间:2012-10-31 19:20:54

标签: sql ms-access

我有两个数据库,我想比较案例出现的次数。

TAB1:

ID     Sequence
A2D    1
A2D    2
A2D    3
A3D    1

TAB2:

ID     Sequence
A2D    1
A2D    2
A3D    1
A3D    2

现在,对于这个例子,我试图得到这个结果:

ID     Table1       Table2
A2D    3            2
A3D    1            2

我尝试过这些代码却没有取得任何成功:

SELECT R1.ID as ID, COUNT(R1.ID) as Table1, 
COUNT(R2.ID) as Table2
FROM TAB1 AS R1, TAB2 AS R2
WHERE R1.ID = R2.ID
GROUP BY R1.ID

这个给了我错误的计数值......

此外,这个只是崩溃:

select 
    ( 
     select count(*) as Table1
     from TAB1
     where ID = R1.ID
    ),(
      select count(*) as Table2
      from TAB2
      where ID= R1.ID
     )
FROM TAB1 AS R1

正如您所看到的,我正在努力让我的标准充满活力。我发现的大多数例子都包括基本的硬编码标准。但对于我的情况,我希望查询查看我的第一个表ID,计算它出现的时间,为具有相同ID的第二个表执行此操作,然后转到下一个ID。

如果我的问题缺乏信息或令人困惑,请问我,我会尽力做到更准确。

提前致谢!

4 个答案:

答案 0 :(得分:0)

这里我使用UNION ALL作为子查询

SELECT ID, SUM(T1) AS Table1, SUM(T2) AS Table2
FROM
    (SELECT ID, COUNT(ID) AS T1,         0 AS T2 FROM TAB1 GROUP BY ID
     UNION ALL
     SELECT ID,         0 AS T1, COUNT(ID) AS T2 FROM TAB2 GROUP BY ID)
GROUP BY ID
HAVING SUM(T1)>0 AND SUM(T2)>0

答案 1 :(得分:0)

不确定我是否理解你的问题,但你可以尝试这样的事情:

SELECT DISTINCT t.ID, 
       (SELECT COUNT(ID) FROM R1 WHERE ID = t.ID) AS table1,
       (SELECT COUNT(ID) FROM R2 WHERE ID = t.ID) AS table2
FROM table1 t

答案 2 :(得分:0)

我使用了不同的方法,但不幸的是我必须使用两个查询,我仍然不知道它们是否可以组合在一起。第一个是用于两个表的总和,并结合结果:

SELECT "Tab1" AS [Table], Tab1.ID, Count(*) AS Total
FROM Tab1
GROUP BY "Tab1", Tab1.ID
UNION SELECT "Tab2" AS [Table], Tab2.ID, Count(*) AS Total
FROM Tab2
GROUP BY "Tab2", Tab2.ID

并且,由于Access支持Pivot查询,您可以使用:

TRANSFORM Sum(qrySums.[Total]) AS Total
SELECT qrySums.[ID]
FROM qrySums
GROUP BY qrySums.[ID]
PIVOT qrySums.[Table];

答案 3 :(得分:0)

为了获得所需的结果,我将其分解为两个子查询(R1SQ和R2SQ)和一个主UNION查询 - 使用内部,左侧和右侧连接的R1R2包括所有行条目,包括那些未出现的行在两个表格中:

<强> R1SQ

SELECT R1.Builder, Count(R1.Builder) AS Table1
FROM R1
GROUP BY R1.Builder;

<强> R2SQ

SELECT R2.Builder_E, Count(R2.Builder_E) AS Table2
FROM R2
GROUP BY R2.Builder_E;

<强> R1R2

SELECT R1SQ.Builder, R1SQ.Table1, R2SQ.Table2
FROM R1SQ INNER JOIN R2SQ ON R1SQ.Builder = R2SQ.Builder_E
UNION
SELECT R1SQ.Builder, R1SQ.Table1, 0 AS Table2
FROM R1SQ LEFT JOIN R2SQ ON R1SQ.Builder = R2SQ.Builder_E
WHERE (((R2SQ.Builder_E) Is Null))
UNION
SELECT R2SQ.Builder_E, 0 AS Table1, R2SQ.Table2
FROM R1SQ RIGHT JOIN R2SQ ON R1SQ.Builder = R2SQ.Builder_E
WHERE (((R1SQ.Builder) Is Null))
ORDER BY R1SQ.Builder;