Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
A little SQL puzzle
Message
 
 
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01444375
Message ID:
01444443
Views:
63
>This is from the top of my head - not tested.
>
>
>Naomi, I appreciate you trying - but untested code that doesn't run,....well, you can guess what I'm about to say. :)
>
>But thanks for giving it a try.

I fixed few minor typos and here is my final version
-- Test query
declare @StudentsScore table (StudentID int primary key, TestScore int)
insert into @StudentsScore select
1, 100
union all select
2, 100
union all select
3, 95
union all select
4, 93
union all select
5, 92
union all select
6, 90
union all select
7, 91
union all select
8, 88
union all select
9, 81
union all select
10, 65
union all select
11, 30
union all select
12, 30


select * from  @StudentsScore order by TestScore, StudentID 

declare @TotalStudents int

select @TotalStudents = count(*) from @StudentsScore

if @TotalStudents%2 = 1
   -- Using integer math logic
    select TestScore from (select *, row_number() over (order by TestScore,StudentID)  as Row from @StudentsScore) X where Row = @TotalStudents/2 + 1
else
   select avg(TestScore*1.0) from (select TestScore from (select *, row_number() 
over (order by TestScore, StudentID)  as Row from @StudentsScore) X where Row = @TotalStudents/2
    union all select TestScore from (select *, row_number() over (order by TestScore, StudentID)  as Row from @StudentsScore) X 
    where Row = @TotalStudents/2 + 1) Y 
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