2011-07-04 152 views
1

我用下面的查询SQL Server 2000中集团在SQL Server 2000中工作,但不能在SQL Server 2005

SELECT 
    U.FirstName, 
    SUM(VE.Score)AS Score, SUM(VE.QuizTime) AS Time, 
    SUM(VE.IsQuizType) AS QuizesAttempted, 
    SUM(VE.IsProgrammingType) AS ProgrammingProblemsAttempted 
from 
    Users U INNER JOIN VirtualExercise VE on U.UserID=VE.UserID 
where U.UserID IN(10,11) AND ProgramID = 2 
group by U.FirstName 
order by VE.Score desc 

它工作正常,在SQL Server 2000,但在SQL Server不工作2005 给出了以下错误:

Column "VirtualExercise.Score" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause. --- Inner Exception

请帮助...

回答

3

SQL Server 2005是正确的:你试图通过不输出,因为你必须要么O组存在的价值订购它或聚合它。 VE.Score既不是。 SQL Server 2000中允许一些模糊之处是这样的(编辑:请参见“ORDER BY子句”在http://msdn.microsoft.com/en-us/library/ms143359(SQL.90).aspx查找有关此信息)

我假定你的意思

ORDER BY SUM(VE.Score) DESC 
0

既然你已经定义在选择SUM(VE.Score)AS Score,你的意思ORDER BY Score DESC

+0

但我的查询在SQL Server 2000中完美运行。它仅在SSQL Server 2005中发生错误。 – jitendra

2

对于结果集中的表和列别名,SQL Server 2000有点笨。提供了明确的别名列,被导入(例如,在你的情况ScoreCol3在下面的例子),也不要紧,你在ORDER使用什么表的别名BY子句:

create table #T1 (
    ID int not null primary key, 
    Col1 varchar(10) not null 
) 
go 
create table #T2 (
    ID int not null primary key, 
    Col2 varchar(10) not null 
) 
go 
insert into #T1 (ID,Col1) 
select 1,'abc' union all 
select 2,'def' 
go 
insert into #T2 (ID,Col2) 
select 1,'zyx' union all 
select 2,'wvu' 
go 
select *,1 as Col3 from #T1 t1 inner join #T2 t2 on t1.ID = t2.ID order by t2.Col3 

既然你大概要排序通过计算Score列,只需删除VE.前缀。

+0

是的,这也是我所指的http://msdn.microsoft.com/zh-cn/library/ms143359(SQL 0.90)的.aspx – gbn