2013-10-04 126 views
2

我在Access 2010數據庫中編寫查詢,該查詢在同一Access 2010數據庫中調用兩個其他查詢。其結果將是一個表格報告具有以下字段:查詢調用兩個其他查詢

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

客戶/列的列表是通過查詢1,這也填充名字,姓氏,HOMEPHONE和客戶編號生成。然後,Query2填充Level,nextDate和Type FOR上述第一個查詢中定義的每個客戶行。

到目前爲止,彙總查詢,我已是:

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; 

但是,當我嘗試在數據表視圖本摘要查詢的結果,訪問給我一個對話框,要求Query2.ClientNumber,這表明代碼中的某些內容沒有正確引用該變量。

僅供參考,這裏是查詢1代碼:

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"); 

有人能告訴我該如何設置,以便它運行正常?

回答

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欄上的連接兩側。

+0

謝謝。 +1爲好的建議。但它比這更微妙一點。 Query2表示WHERE ClientNumber = 1。但是,WHERE條件中的ClienNumber的值需要爲每行更改,以便連接爲Query1返回的每一行列出填充值或空值。彙總查詢現在輸出空行,但顯示所有7個字段的標籤。你能否提出一種改變語法的方法,以便在Query2的「WHERE ClientNumber = 1」部分中將Query1中的變量替換爲Query1中的變量? – CodeMed

+1

@CodeMed如你所述,Query2子查詢中的WHERE子句只會返回'ClientNumber = 1'的值。如果您想獲取所有客戶端的結果(ClientNumber值),則需要刪除這些WHERE子句並將ClientNumber添加到GROUP BY子句中。然後,「Query2」將返回所有客戶端的行,並且當您在其他查詢中引用「Query2」時,您可以在其他表/查詢的JOIN中使用(現在可見的)ClientNumber字段。 –

+0

@GordThompson我希望你知道你的見解是非常感謝。謝謝。 – CodeMed