查询调用其他两个查询

时间:2013-10-04 21:20:34

标签: sql ms-access ms-access-2010

我正在Access 2010数据库中编写一个查询,该数据库在同一个Access 2010数据库中调用另外两个查询。结果将是一个包含以下字段的表格报告:

FirstName, LastName, HomePhone, ClientNumber, Level, nextDate, Type 

客户/行列表由Query1生成,它还会填充FirstName,LastName,HomePhone和Client Number。然后,Query2填充上面第一个查询中定义的Level,nextDate和Type FOR EACH客户行。

到目前为止,我的摘要查询是:

SELECT Query1.FirstName, Query1.LastName, Query1.HomePhone, Query1.ClientNumber, Query2.[Level], Query2.nextDate, Query2.Type 
FROM Query1 
INNER JOIN Query2 ON Query1.ClientNumber=Query2.ClientNumber;  

但是当我尝试在数据表视图中查看此摘要查询的结果时,Access为我提供了一个对话框,询问Query2.ClientNumber,它指示代码中的某些内容未正确引用该变量。

供参考,以下是Query1的代码:

SELECT ActiveCustomers.FirstName, ActiveCustomers.LastName, tblClientAddress.HomePhone, ActiveCustomers.ClientNumber 
FROM 
(
    SELECT Clients.ClientNumber, Clients.FirstName, Clients.LastName   
    (     
        SELECT COUNT(ReferralDate)      FROM IntakeTable      WHERE Clients.ClientNumber = IntakeTable.ClientNumber AND Len(ReferralDate & '') > 0   
    ) AS IntakeCount, 
    (     
        SELECT COUNT(ExitDate)      FROM ExitTable      WHERE Clients.ClientNumber = ExitTable.ClientNumber AND Len(ExitDate & '') > 0   
    ) AS ExitCount 
FROM Clients
)  AS ActiveCustomers  
INNER JOIN tblClientAddress ON ActiveCustomers.ClientNumber=tblClientAddress.ClientNumber
WHERE IntakeCount > ExitCount  AND tblClientAddress.CurrentResidence = True;  

以下是Query2的代码:

SELECT a.[Level], max(a.dte) AS nextDate, IIf([Type1Date]<[Type2Date],"t1","t2") AS [Type]
FROM (
    select [Level], Type1Date as dte
    FROM CommunicationTable WHERE ClientNumber=1  
    UNION
    select [Level], Type2Date as dte
    FROM CommunicationTable WHERE ClientNumber = 1  
)  AS a
GROUP BY a.[Level], IIf(a.[Type1Date]<a.[Type2Date],"t1","t2");  

有人可以告诉我如何设置它以便它正常运行吗?

1 个答案:

答案 0 :(得分:2)

当您加入和嵌套这样的查询时,它有助于描绘外部查询“暴露”的内容。 Query2有一个嵌套查询a,但不会公开ClientNumber,因此Query2无法(并且不会尝试)将ClientNumber公开给加入。试试Query2

SELECT a.[Level], max(a.dte) AS nextDate, IIf([Type1Date]<[Type2Date],"t1","t2") AS [Type], a.ClientNumber
FROM (
    select [Level], Type1Date as dte, ClientNumber
    FROM CommunicationTable WHERE ClientNumber=1  
    UNION
    select [Level], Type2Date as dte
    FROM CommunicationTable WHERE ClientNumber = 1  
)  AS a
GROUP BY a.[Level], IIf(a.[Type1Date]<a.[Type2Date],"t1","t2");

这样,外部查询可以“看到”连接两侧的ClientNumber列。