1

My assignment is: I have a table called Results(codeCompetition, Contestant, place). I need to make a select that shows: Contestant, nr_points where nr_points = 10 if the place of the contestant, for that competition was 1, nr_points = 8 for 2nd place and nr_points = 5 for 3rd place.

go
create view Loc1 as
select Rezultate.sportiv, sum(10) as puncte from Rezultate
where loc_ocupat = '1'
group by sportiv
go

go
create view Loc2 as
select Rezultate.sportiv, sum(8) as puncte from Rezultate
where loc_ocupat = '2'
group by sportiv
go

go
create view Loc3 as
select Rezultate.sportiv, sum(5) as puncte from Rezultate
where loc_ocupat = '3'
group by sportiv
go

-- create view
go
create view total_result as
select * from Loc1 union select * from Loc2 union select * from Loc3
go

-- sum of all the points from every competition that a contestant participated
select total_result.sportiv, SUM(total_result.puncte) as total_puncte from total_result
group by total_result.sportiv

Now this code works ok, but I'm not sure it is the easiest answer. Is there any kind of condition with multiple choices in T-SQL ? (without creating a new table, column)

I'm looking for something like:

if(place == 1)    
  add(10_points)
if(place == 2)
  add(8_points)
..............

1 Answer 1

1

You can use CASE statement and use the following one sql query:

select sportiv, 
SUM( CASE WHEN loc_ocupat = '1' THEN 10
          WHEN loc_ocupat = '2' THEN 8
          WHEN loc_ocupat = '3' THEN 5
     END
) as total_puncte 
from Rezultate
group by sportiv
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.