1

我的任务是:我有一个名为 Results(codeCompetition, Contestant, place) 的表。我需要进行选择以显示:参赛者,nr_points 其中 nr_points = 10 如果参赛者的位置是 1,nr_points = 8 为第二名,nr_points = 5 为第三名。

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)
..............
4

1 回答 1

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
于 2013-01-17T07:03:32.657 回答