我正在学习psql,并且与CASE关键字相混淆。
说我有一张桌子“宠物”。
name | species | owner | gender | color
-------------+---------+--------------------+--------+---------------
Nagini | snake | Lord Voldemort | female | green
Hedwig | owl | Harry Potter | female | snow white
Scabbers | rat | Ron Weasley | male | unspecified
Pigwidgeon | owl | Ron Weasley | male | grey
Crookshanks | cat | Herminone Granger | male | ginger
Mrs Norris | cat | Argus Filch | female | dust-coloured
Trevor | toad | Neville Longbottom | male | brown
我被问到了 “使用CASE显示宠物名称和一列,以表明宠物的名字是长还是短(长名称长度超过6个字符)。过滤只选择女性宠物。”
官方文档仅提供仅使用CASE的示例。当我尝试解决问题时,我尝试了
SELECT *
CASE
WHEN name > 6 THEN
msg:= 'long'
ELSE
msg:= 'short'
END CASE
FROM pets WHERE gender = 'female';
给了我一个错误ERROR: syntax error at or near "CASE"
我可以将CASE与SELECT语句结合使用吗?如果有,怎么样?如果不是,我怎么能解决上述任务?
答案 0 :(得分:4)
根据PostgreSQL文档(https://www.postgresql.org/docs/current/static/functions-conditional.html),案例表达的正确方法是:
CASE WHEN condition THEN result
[WHEN ...]
[ELSE result]
END
根据您发布的代码,当END应该为END时,您将使用END CASE结束表达式。你也忘了在星号后加一个逗号。我会用以下方式编写您的查询:
SELECT *,
CASE
WHEN length(name) > 6 THEN 'long'
ELSE 'short'
END as msg
FROM pets WHERE gender = 'female';