2

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

请指教。

4

4 回答 4

4

您不能使用ALIAS在查询的同一级别上创建的那个,

SELECT AUTHOR, COUNT(AUTHOR) AS CAL, 
       CASE WHEN COUNT(AUTHOR)>1 THEN 'MULTIPLE' ELSE 'SINGLE' END 
FROM MANGATABLE 
GROUP BY AUTHOR

操作顺序如下:

  • FROM 子句
  • WHERE 子句
  • GROUP BY 子句
  • HAVING 子句
  • 选择子句
  • ORDER BY 子句

别名是在SELECT子句上创建的,这就是您不能使用它的原因。

于 2013-03-22T10:01:38.160 回答
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表达式将公共部分排除在外,从而避免这种情况。

(是的,您可以通过为 case 表达式指定别名来更改列标题 - 我已将其添加到其中。)

于 2013-03-22T10:01:49.563 回答
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
于 2013-03-22T10:09:57.677 回答
0

你应该只需要一点点改变,见下文

SELECT 
    AUTHOR, 
    COUNT(AUTHOR) AS CAL, 
    CASE WHEN COUNT(AUTHOR) THEN 'MULTIPLE' ELSE 'SINGLE' END     
FROM MANGATABLE GROUP BY AUTHOR
于 2013-03-22T10:01:36.777 回答