我有这样的代码,工作正常:
select count (CAST(faculty AS NVARCHAR(MAX))) as num
from student
group by CAST(faculty AS NVARCHAR(MAX))
faculty
是一个文字。但是我需要计算一列中的教师数量,所以尝试了这个代码,它给出了错误: Column' student.faculty'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
select faculty, count (CAST(faculty AS NVARCHAR(MAX))) as num
from student
group by CAST(faculty AS NVARCHAR(MAX))
我无法理解,问题在哪里,因为同样的方法适用于数字。例如这一个:
select id, count(id)
from student
group by id
我做错了什么?
答案 0 :(得分:2)
您收到错误,因为您没有按照您选择的相同分组
CAST(faculty AS NVARCHAR(MAX))
不等于faculty
。为什么不使用:
select faculty, count (*) as num
from student
group by faculty
答案 1 :(得分:1)
试试这个
select count(CAST(faculty AS NVARCHAR(MAX))) as num ,
CAST(faculty AS NVARCHAR(MAX)) facultys
from student
group by facultys