Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
A little SQL puzzle
Message
 
 
To
18/01/2010 09:41:32
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01444375
Message ID:
01444550
Views:
41
>>
>>set statistics time on
>>set statistics profile on
>>set statistics io on
>>print 'Creating cte'
>>;with cte as (select *, row_number() 
>>over (order by TestScore, StudentID)  as Row from @StudentsScore)
>>
>>   select avg(TestScore*1.0) from (select TestScore from cte where Row = (@TotalStudents+1)/2
>>    union all select TestScore from cte 
>>    where Row = (@TotalStudents+2)/2) Y 
>>print 'Finished with the UNION select'
>>print 'Creating cte'
>>;with cte as (select *, row_number() 
>>over (order by TestScore, StudentID)  as Row from @StudentsScore)
>>
>>   select avg(TestScore*1.0) from cte where Row between (@TotalStudents+1)/2 and (@TotalStudents+2)/2
>>print 'Finished with the BETWEEN select'   
>>set statistics io off
>>set statistics profile off
>>set statistics time off
>>
>
>
>The thing is that union always take two records whilst between takes 1 record if TotalStudents is odd and 2 if TotalStudents is even
>
>(@TotalStudents+1)/2 equals (@TotalStudents+2)/2 if TotalStudents is odd
>
>
>TotalStudents = 3
>(@TotalStudents+1)/2  = (3+1)/2 = 2
>(@TotalStudents+2)/2 = (3+2)/2 = 2
>
>
>
>TotalStudents = 4
>(@TotalStudents+1)/2  = (4+1)/2 = 2
>(@TotalStudents+2)/2 = (4+2)/2 =3
>
You're right. For this problem between is clearly a winner.
If it's not broken, fix it until it is.


My Blog
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform