[SQL CASE WHEN]为什么当我同时指定两个条件时 case when 不起作用?

[SQL CASE WHEN]Why case when is not working when I specify two conditions at the same time?

您好,我正在尝试从 datacamp 获得的 SQL 查询的不同版本。

我得到的查询是

SELECT 
    date,
    -- Identify the home team as Barcelona or Real Madrid
    case when hometeam_id = 8634 then 'FC Barcelona' 
        else 'Real Madrid CF' end as home,
    -- Identify the away team as Barcelona or Real Madrid
    case when awayteam_id = 8634 then 'FC Barcelona' 
        else 'Real Madrid CF' end as away
FROM matches_spain
WHERE (awayteam_id = 8634 OR hometeam_id = 8634)
      AND (awayteam_id = 8633 OR hometeam_id = 8633);

我试着调整一下
思考,“与其为每个案例场景设置一个条件,不如通过将两个条件与 'and 连接起来同时设置两个条件”
我的查询如下。

select date,
case when hometeam_id=8634 and awayteam_id = 8633 then 'FC Barcelona'
     when hometeam_id=8633 and awayteam_id = 8634 then 'Real Madrid CF'
     end as home,
case when hometeam_id=8633 and awayteam_id = 8634 then 'Real Madrid CF'
     when hometeam_id=8634 and awayteam_id = 8633 then 'FC Barcelona'
     end as away
from matches_spain
where (hometeam_id=8634 and awayteam_id=8633)
or (hometeam_id=8633 and awayteam_id=8634)

teams_spain table是这样的

matches_spain table是这样的

"matches_spain" 是某个赛季的足球比赛记录,有主队id和客队id。每个团队都有自己的唯一 ID,可以在 teams_spain table.

中找到唯一 ID


为什么我的替代代码打印出错误的输出?

理想的输出是 我的错误输出是

除了我不明白你为什么要像你那样改变逻辑之外,你正在为主队和客队使用相同的 CASE WHEN 结构,所以你当然会得到他们的结果相同。第二个 CASE WHEN 不正确。您写道:

case when hometeam_id=8633 and awayteam_id = 8634 then 'Real Madrid CF'
 when hometeam_id=8634 and awayteam_id = 8633 then 'FC Barcelona'
 end as away

...反之亦然:

case when hometeam_id=8634 and awayteam_id = 8633 then 'Real Madrid CF'
 when hometeam_id=8633 and awayteam_id = 8634 then 'FC Barcelona'
 end as away