如何在SQL中引用具有计数的列?

问题描述

如何获取“ count(division)”列而不是实际计数?

select * from num_taught;

给我这个

enter image description here

select count(division) from num_taught;

给我这个,但我实际上想要上一张图像的第三列“ count(division)”

enter image description here

我想知道这一点,因为我现在正在这样做:

    sql> select * from num_taught as a,num_taught as b
...> where a.count(division) = b.count(division);
Error: near "(": Syntax error

但是正如您所看到的,存在语法错误,我认为这是因为代码没有引用“ count(division)”列,而是实际上找到了计数。

我的最终目标是输出具有相同“分区”和相同计数(分区)的“标题”。

例如,终端表将具有“首席会计师”,“程序员培训生”,“雕刻家”,“技术员”,“向导”行。由于这些行的除法和count(division)匹配

谢谢!

解决方法

DESC num_taught返回什么?我很好奇第三列的填充方式-是某种伪列吗?您可能需要尝试用[]包裹列名,请参见:How to deal with SQL column names that look like SQL keywords?

即尝试:

select [count(division)] from num_taught;
,

我认为您只想要一个count(distinct)

select count(distinct division)
from num_taught;
,

您需要使用引号对列名进行转义(以防您在注释中提到的Sqlite)。

select "count(division)" from num_taught;

或:

select * from num_taught as a,num_taught as b
 where a."count(division)" = b."count(division)";

如果不这样做,则使用的是数据库系统提供的计数功能。 像这样命名一列是非常不寻常的,它可能是您的导师的陷阱,也可能是初始化表时的错误。