我的任务是: 我有一个名为Results(codeCompetition,Contestant,place)的表。我需要做一个选择,显示:参赛者,nr_points,其中nr_points = 10,如果参赛者的位置,该比赛为1,nr_points = 8为第2名,nr_points = 5为第3名。
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
现在这段代码工作正常,但我不确定这是最简单的答案。在T-SQL中有多种选择的条件吗? (不创建新表,列)
我正在寻找类似的东西:
if(place == 1)
add(10_points)
if(place == 2)
add(8_points)
..............
答案 0 :(得分:1)
您可以使用CASE语句并使用以下一个SQL查询:
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