Insert into dbo.Cache(StringSearched, ColName, RowId, PercentMatch) select ValFromUser, ColumnName, RowNumber, Max(Percentage) from #Temp2 Group by ValFromUser, ColumnName, RowNumber order By Percentage desc
上面的SQL语句给出了如下错误:
Column "#Temp2.Percentage" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
我使用了MAX
函数和百分比,即MAX(Percentage)
,但我得到了上述错误。我该怎么解决这个问题?
答案 0 :(得分:2)
您应该为列添加别名,然后您可以按顺序使用它。
Insert into dbo.Cache(
StringSearched,
ColName,
RowId,
PercentMatch)
select
ValFromUser,
ColumnName,
RowNumber,
Max(Percentage) as MaxPerc
from
#Temp2
Group by
ValFromUser,
ColumnName,
RowNumber
order By
MaxPerc desc
此外,除非您的表具有标识字段或类似字段,否则使用order by with insert是没有意义的。
答案 1 :(得分:1)
以这种方式维护表中的顺序或多或少是没有意义的,因为除非您在检索时包含订单,否则不能保证以任何特定顺序返回行。
也就是说,您可以按顺序重复使用该功能:
Insert into dbo.Cache (StringSearched, ColName, RowId, PercentMatch)
select ValFromUser, ColumnName, RowNumber, Max(Percentage)
from #Temp2
Group by ValFromUser, ColumnName, RowNumber
Order By max(Percentage) desc
或者给ccolumn一个别名并使用它:
Insert into dbo.Cache (StringSearched, ColName, RowId, PercentMatch)
select ValFromUser, ColumnName, RowNumber, Max(Percentage) Perc
from #Temp2
Group by ValFromUser, ColumnName, RowNumber
Order By Perc Desc