2013-12-18 50 views
1

我試圖通過UNION組合多個查詢。當我嘗試執行時,出現以下錯誤:UNION查詢錯誤 - 「您試圖執行不包括指定表達式的查詢...」

「您試圖執行不包含指定表達式'DateRec'作爲聚合函數一部分的查詢。」

任何想法?

這是我的查詢。

SELECT [Leads Received by Agent].DateRec, [Leads Received by Agent].AgentID, 
    [Leads Received by Agent].AgentFirstName, [Leads Received by Agent].AgentLastName, 
    Count([Leads Received by Agent].LastAction) AS CountOfLastAction, 
    'Leads Received by Agent' as type 
FROM [Leads Received by Agent] 

UNION ALL 

SELECT [Leads Proposed by Agent].DateRec, [Leads Proposed by Agent].AgentID, 
    [Leads Proposed by Agent].AgentFirstName, [Leads Proposed by Agent].AgentLastName, 
    Count([Leads Proposed by Agent].LastAction) AS NumofLeadsProp, 
    'Leads Proposed by Agent' 
FROM [Leads Proposed by Agent] 

ORDER BY [Leads Received by Agent].DateRec; 
+0

如果您需要進行一系列操作,您需要按照daterec,agentid,agentfirstname,agentlastname和TYPE進行分組。在兩個工會。 – xQbert

+1

您需要在兩個選擇上沒有聚合函數的列上使用GROUP BY。 – Mihai

回答

2

by子句添加組分別如下,以工會的各佔一半,例如...

SELECT [Leads Received by Agent].DateRec, 
     [Leads Received by Agent].AgentID, 
     [Leads Received by Agent].AgentFirstName, 
     [Leads Received by Agent].AgentLastName, 
     Count([Leads Received by Agent].LastAction) AS CountOfLastAction, 
     'Leads Received by Agent' as type 
FROM [Leads Received by Agent] 
GROUP BY [Leads Received by Agent].DateRec, 
     [Leads Received by Agent].AgentID, 
     [Leads Received by Agent].AgentFirstName, 
     [Leads Received by Agent].AgentLastName,'Leads Received by Agent' as type 

而且,我不建議「類型」爲列別名,因爲它is a reserved word

+2

http://support.microsoft.com/kb/286335類型是2002+中的保留字 – xQbert