1

私の課題は次のとおりです。Results(codeCompetition、Contestant、place) というテーブルがあります。次のような選択を行う必要があります: Contestant, 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)
..............
4

1 に答える 1

1

CASEステートメントを使用して、次の 1 つの 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 に答える