帮助“GROUP BY子句”错误

时间:2009-12-07 04:51:28

标签: max aggregate-functions

希望任何人都可以帮我解决这个错误“列'Sales.No_'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。”... 我花了几天时间来理解这个错误但是失败了:( 我的查询: -

SELECT SH.[No_], SH.[Sell-to Customer No_], SH.[Sell-to Contact No_],
SH.[Sell-to Customer Template Code], MAX (A.[Version No_]) 
FROM [Sales] AS SH 
LEFT JOIN [Sales Archive] A ON (SH.[Document Type] = A.[Document Type] 
                 AND SH.[No_]=A.[No_] 
                 AND SH.[Doc_ No_ Occurrence]=A.[Doc_ No_ Occurrence]) 
WHERE (SH.[Document Type]='0' and SH.[Order]='1')

2 个答案:

答案 0 :(得分:2)

如果您有非聚合列,则“MAX”函数需要group by。 所以你需要通过sh添加一个组。[No _] ....

此外,我已经重新格式化了您的查询,因此我可以更轻松地阅读 - 希望这是好的 -

select SH.[No_]
, SH.[Sell-to Customer No_]
, SH.[Sell-to Contact No_]
, SH.[Sell-to Customer Template Code]
, MAX (A.[Version No_]) 
from [Sales] AS SH 
    LEFT JOIN [Sales Archive] A ON 
        (SH.[Document Type] = A.[Document Type] 
          AND SH.[No_]=A.[No_] 
          AND SH.[Doc_ No_ Occurrence]=A.[Doc_ No_ Occurrence]
        ) 
where (SH.[Document Type]='0' and SH.[Order]='1')
group by SH.[No_]
       , SH.[Sell-to Customer No_]
       , SH.[Sell-to Contact No_]
       , SH.[Sell-to Customer Template Code]

答案 1 :(得分:0)

这是因为您使用了聚合函数(MAX),因此剩余的选定列也必须使用聚合函数或group by子句。例如

select SH.[No_],SH.[Sell-to Customer No_],SH.[Sell-to Contact No_],
SH.[Sell-to Customer Template Code],MAX (A.[Version No_])
from [Sales] AS SH LEFT JOIN [Sales Archive] A ON (SH.[Document Type] = A.[Document Type]
AND SH.[No_]=A.[No_] AND SH.[Doc_ No_ Occurrence]=A.[Doc_ No_ Occurrence])
where (SH.[Document Type]='0' and SH.[Order]='1')
group by SH.[No_],SH.[Sell-to Customer No_],SH.[Sell-to Contact No_],
SH.[Sell-to Customer Template Code]