从MYTABLE组中按列选择COUNT(列)无效

时间:2019-03-22 19:16:40

标签: sql sql-server

我的SQL服务器中有三个这样的表。

  • 主题:IDsub01 NameSub01

  • 老师:IDTeacher01 NameTeacher01

  • 考试:IDExam01 IDTeacher01 IDsub01
    考试:IDExam02 IDTeacher01 IDsub01
    考试:IDExam03 IDTeacher01 IDsub01

我要收集数据:

IDsub01    Namesub01    3

这意味着该科目具有IDsub01,并且IDTeacher01进行了3项考试。我尝试了此SQL语句,但不起作用

SELECT 
    s.IDsub, s.NameSub, COUNT(t.IdTeacher) 
FROM 
    subjects s, teacher t, exam e 
WHERE 
    t.IdTeacher = e.IdTeacher 
    AND e.IDSubject = s.IDSubject 
    AND t.IDTeacher = "IDTeacher01" 
GROUP BY
    t.IDTeacher

我遇到错误

  

列“ s.NameSub”在选择列表中无效,因为该列未包含在聚合函数或GROUP BY子句中。

2 个答案:

答案 0 :(得分:4)

错误的分组依据

SELECT s.IDsub, s.NameSub, count(t.IdTeacher) 
FROM subjects s, teacher t, exam e 
WHERE t.IdTeacher = e.Is.IDsub, s.NameSubdTeacher 
     and e.IDSubject = s.IDSubject 
        and t.IDTeacher = 'IDTeacher01'
    group by  s.IDsub, s.NameSub

无论如何,您应该避免基于何处的旧的隐式联接sintax,并使用显式联接sintax作为

    SELECT s.IDsub, s.NameSub, count(t.IdTeacher) 
    FROM subjects s
    INNER JOIN teacher t ON t.IdTeacher = e.Is.IDsub 
    INNER JOIN  exam e ON s.NameSubdTeacher and e.IDSubject
    WHERE  t.IDTeacher = 'IDTeacher01' 
    group by  s.IDsub, s.NameSub

并对文字字符串使用单引号

答案 1 :(得分:0)

由于加入条件中select vs IDSubject中的IDsub拼写错误,导致出现错误。另外,除了在“ group by”子句中的列之外,还必须在select中枚举的每个列上使用聚合函数。
正确的子句可以是:

=FILTER(IMPORTRANGE("1gyAaxDzklUuhwBdLpMkb2jgrPmbJ9WxtdJ1JOO2d424","Responses!N1:N101"),
 ROW(A1:A101)=MAX(FILTER( ROW(A1:A101),NOT(
 ISBLANK(IMPORTRANGE("1gyAaxDzklUuhwBdLpMkb2jgrPmbJ9WxtdJ1JOO2d424","Responses!N1:N101"))))))

http://sqlfiddle.com/#!18/d286a/4/0上查看解决方案