【问题标题】:ODBC SQL IIF With Group By - Aggregate Function Error带有 Group By 的 ODBC SQL IIF - 聚合函数错误
【发布时间】:2016-05-27 01:54:22
【问题描述】:

这是我要运行的 ODBC SQL 语句。 ODBC 是连接类型,查询针对 Excel 电子表格的命名范围运行。我能说的最好的 SQL 已被使用,并且所有先前的查询都按预期工作。

select
IIF([Account Name]='Account1','Special Account','Not Special') as AccountType,
IIF([Recipe]='Recipe1','American','Other') as FoodType,
sum([Unpaid])
from MyData
Group by [Account Name]

这是我收到的错误消息。

“您尝试执行的查询不包含指定表达式作为聚合函数的一部分。”

我知道这意味着我必须将 [Recipe] 添加到 Group by 以便 Group by 看起来像这样。

Group by [Account Name],[Recipe]

如果我进行此更改,SQL 语句会运行,但我不能通过两个字段输出 Group。这将返回我不使用且无法使用的结果。我真的只想按 [Account Name] 分组。

我该怎么做?此查询中需要 IIF 语句来返回所需的结果。

【问题讨论】:

    标签: sql group-by iif


    【解决方案1】:

    如果它不在聚合函数中,则它需要在 group by 中。 SUM() 是您拥有的唯一聚合函数 - 其他函数按分组排列。

    select
    IIF([Account Name]='Account1','Special Account','Not Special') as AccountType,
    IIF([Recipe]='Recipe1','American','Other') as FoodType,
    sum([Unpaid])
    from MyData
    Group by IIF([Account Name]='Account1','Special Account','Not Special'),
    IIF([Recipe]='Recipe1','American','Other')
    

    【讨论】:

    • 我知道我必须添加到 Group by,但这并不能解决我的问题,因为添加到 group by 网络结果我无法使用。我在问题中提到了这一点。
    • @user2027231 您的问题是按列名分组,我按 IIF 语句分组。也许用您期望的输出更新您的问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 2014-08-24
    • 2013-12-03
    相关资源
    最近更新 更多