2

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

选项卡1:

ID     Sequence
A2D    1
A2D    2
A2D    3
A3D    1

选项卡2:

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

4 回答 4

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
于 2012-10-31T20:22:59.763 回答
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
于 2012-10-31T20:30:14.463 回答
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];
于 2012-10-31T20:35:22.383 回答
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;
于 2012-10-31T20:59:32.187 回答