我正在尝试在SELECT语句中使用COUNT(*)。但是,我需要重命名它并能够在WHERE子句中引用它。
我已经尝试过使用AS,并且尝试省略了AS,因为根据oracle页面,step by step guide
似乎没有必要尝试将新标识符用引号引起来,但这也不起作用。
这可行,但是给计数指定一个由oracle生成的名称,这并不理想,而且我不知道如何引用每一行的计数:
SELECT
school_name,
(SELECT COUNT(*)
FROM liason_to
WHERE school_name = s.school_name)
FROM school s;
这是我尝试过的但无法使用的方法:
SELECT
school_name,
(SELECT COUNT(*) AS numLiasons
FROM liason_to
WHERE school_name = s.school_name)
FROM school s
WHERE numLiasons > 0;
它没有使列名称为“ numLiasons”,并且末尾的where子句不知道numLiasons是什么,所以失败了。
答案 0 :(得分:1)
您可以使用..进行联接和分组来避免子查询,并且可以将您喜欢的主题分配为别名
SELECT s.school_name, COUNT(*) as my_count
FROM school s
INNER JOIN liason_to l on s.school_name = l.school_name
GROUP BY s.school_name
使用您的代码,您只需在(subselected)列中分配一个别名
SELECT
school_name,
(SELECT COUNT(*)
FROM liason_to
WHERE school_name = s.school_name) as my_name
FROM school s;
无论如何,您可以使用除count(*)
以外的所有结果进行过滤
请记住,此功能仅适用于非空行,因此通常count(*)> 0
答案 1 :(得分:1)
您可以通过在列后面加上一个名称来为列加上别名,还可以在它们之间使用关键字AS
。基本上与您对表格所做的相同。
SELECT school_name,
(SELECT count(*)
FROM liason_to l
WHERE l.school_name = s.school_name) AS numliasons
FROM school s;
或者简单地
SELECT school_name,
(SELECT count(*)
FROM liason_to l
WHERE l.school_name = s.school_name) numliasons
FROM school s;
但是您不能在WHERE
子句中使用别名(别名已经在WHERE
子句中选择了记录之后发生)。您必须重复这次尝试。
SELECT school_name,
(SELECT count(*)
FROM liason_to l
WHERE l.school_name = s.school_name) numliasons
FROM school s
WHERE (SELECT count(*)
FROM liason_to l
WHERE l.school_name = s.school_name) > 0;
答案 2 :(得分:0)
您不能在WHERE子句中引用别名,但是您可以这样做:
SELECT
t.school_name,
t.numLiasons
FROM (
SELECT
s.school_name,
(
SELECT COUNT(*)
FROM liason_to
WHERE school_name = s.school_name
) AS numLiasons
FROM school s
) t
WHERE t.numLiasons > 0;