2011-07-04 153 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