SQL,根据其他列选择列

时间:2019-05-21 12:11:02

标签: sql

对于学校项目,我编写了一个UFC数据库。我不知道如何写一些查询。 一张桌子是关于战斗的

FIGHT:


 - Id_fight, integer, PK
 - Fighter1, integer, FK
 - Fighter2, integer, FK
 - Judge, integer, FK
 - WhichGala, integer, FK
 - HowManyRounds, integer
 - WhoWon, integer
 - HowWon, varchar2(50)

要知道获胜者,我创建了一个WhoWon列,可以为1(fighter1获胜)或2(fighter2获胜)。我想创建一些查询,但我不知道如何赢得比赛的胜利者。

查询: -重复显示所有战斗中的所有获胜者。

1 个答案:

答案 0 :(得分:1)

用例:

select distinct -- removes the duplicates
         case when WhoWon = 1 then Fighter1
              when WhoWon = 2 then Fighter2
              else 'Tied fight'
         end as Winners
from Mytable

您还可以算出他们赢得了多少:

select Winners, count(*) as fightswon
from
(
    select   case when WhoWon = 1 then Fighter1
                  when WhoWon = 2 then Fighter2
                  else 'Tied fight'
             end as Winners, ID_FIGHT
    from Mytable
)
-- Add any joins or where clauses here
group by Winners