UNION 查询错误 - “您已尝试执行不包含指定表达式的查询...”

Posted

技术标签:

【中文标题】UNION 查询错误 - “您已尝试执行不包含指定表达式的查询...”【英文标题】:UNION Query Error - "You have tried to execute a query that does not inlude the specified expression..." 【发布时间】:2013-12-18 20:14:15 【问题描述】:

我正在尝试通过 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;

【问题讨论】:

如果您想要操作计数,您需要按 daterec、agentid、agentfirstname、agentlastname 和 TYPE 分组。在两个工会中。 您需要对两个选择都没有聚合函数的列进行 GROUP BY。 【参考方案1】:

在联合的每一半中添加如下的group 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。

【讨论】:

以上是关于UNION 查询错误 - “您已尝试执行不包含指定表达式的查询...”的主要内容,如果未能解决你的问题,请参考以下文章

UNION 查询错误

Laravel 4 - Union + orederBy 结果错误查询

mysql数据库多个表union all查询并排序的结果为啥错误

mysql数据库多个表union all查询并排序的结果为啥错误

SQL Select - Union 结合 Join 查询导致错误

使用 UNION ALL 查询在 FROM 子句中出现语法错误