SQL中的初学者,我试图使用CASE
来做一些条件操作。
我有一个名为MangaTable
的表格,其中包含一些漫画(漫画)的详细信息,如标题,作者等。我正在尝试GROUP
作者看看他们有多少这样的头衔:
SELECT AUTHOR, COUNT(AUTHOR) FROM MANGATABLE GROUP BY AUTHOR
我得到了这样的数据:
"Masashi Kishimoto" | 1
"Eiichiro Oda" | 1
"Tsugumi Ohba" | 1
"Kubo Tite" | 2
但是我想要显示“单个”或“多个”而不是数字。 我试过这个:
SELECT AUTHOR, COUNT(AUTHOR) AS CAL, CASE WHEN CAL>1 THEN 'MULTIPLE' ELSE 'SINGLE' END FROM MANGATABLE GROUP BY AUTHOR
但我收到错误:column "cal" does not exist
请指教。
答案 0 :(得分:4)
您无法使用在同一级别的查询中创建的ALIAS
SELECT AUTHOR, COUNT(AUTHOR) AS CAL,
CASE WHEN COUNT(AUTHOR)>1 THEN 'MULTIPLE' ELSE 'SINGLE' END
FROM MANGATABLE
GROUP BY AUTHOR
操作顺序如下:
别名是在SELECT
子句上创建的,这就是你不能使用它的原因。
答案 1 :(得分:1)
您无法通过选择列表中的别名引用选择列表中的表达式 - 如果您将其更改为:
SELECT AUTHOR,
COUNT(AUTHOR) AS CAL,
CASE WHEN COUNT(AUTHOR)>1 THEN 'MULTIPLE' ELSE 'SINGLE' END AS AUTHOR_TYPE
FROM MANGATABLE
GROUP BY AUTHOR
不幸的是不得不再次重复表达 - 这是SQL的缺陷之一。
您有时可以使用WITH表达式来避免这种情况,从而将公共部分考虑在内。
(是的,您可以通过为案例表达式指定别名来更改列标题 - 我已将其添加到。)
答案 2 :(得分:0)
您只需要进行一些小改动,请参阅下文
SELECT
AUTHOR,
COUNT(AUTHOR) AS CAL,
CASE WHEN COUNT(AUTHOR) THEN 'MULTIPLE' ELSE 'SINGLE' END
FROM MANGATABLE GROUP BY AUTHOR
答案 3 :(得分:0)
使用临时表
SELECT CASE z.CAL WHEN 1 THEN 'MULTIPLE' ELSE 'SINGLE' END FROM (SELECT AUTHOR,
COUNT(AUTHOR) AS CAL FROM MANGATABLE GROUP BY AUTHOR) as z
<强>校正强>
SELECT (CASE WHEN z.CAL > 1 THEN 'MULTIPLE' ELSE 'SINGLE' END) as test FROM (SELECT AUTHOR,
COUNT(AUTHOR) AS CAL FROM MANGATABLE GROUP BY AUTHOR) as z