我有以下Oracle SQL查询。给定给定的名称和姓氏,它以任一顺序查找具有一个名称和另一个名称的初始值的所有记录。我创建了score
列,将可能的匹配项放在结果集的顶部。
SELECT
surname,
givenname,
(CASE WHEN surname = 'Smith' THEN 2 ELSE 0)
+ (CASE WHEN givenname = 'John' THEN 1 ELSE 0)
AS score
FROM person
WHERE (surname = 'Smith' AND givenname LIKE 'J%')
OR (surname LIKE 'S%' AND givenname = 'John')
OR (surname = 'John' AND givenname LIKE 'S%')
OR (surname LIKE 'J%' AND givenname = 'Smith')
ORDER BY
score DESC,
surname ASC,
givenname ASC;
问题是score
在+
的位置发出错误。 IDE报告:
语法错误,预期:
/
*
|
执行报告:
SQL错误:ORA-00905:缺少关键字
我做错了什么?有没有更好的方法来计算分数?
答案 0 :(得分:4)
您错过了END
声明中的CASE
:
SELECT
surname,
givenname,
(CASE WHEN surname = 'Smith' THEN 2 ELSE 0 END) -- < add END
+ (CASE WHEN givenname = 'John' THEN 1 ELSE 0 END) -- < add END
AS score
FROM person
WHERE (surname = 'Smith' AND givenname LIKE 'J%')
OR (surname LIKE 'S%' AND givenname = 'John')
OR (surname = 'John' AND givenname LIKE 'S%')
OR (surname LIKE 'J%' AND givenname = 'Smith')
ORDER BY
score DESC,
surname ASC,
givenname ASC;