0

执行选择后,我收到错误“'where 子句'中的未知列'points'

如何从外部查询中删除包含从子查询返回的空记录的行?(我需要使用子查询,因为我还有一堆子查询需要运行才能返回我所追求的结果)

SELECT  
   s.student_name_first,
   s.student_name_last,
   (
   SELECT sum(i.points)
   FROM incidents i
   WHERE i.student = s.id
   ) AS points
FROM students s
WHERE points IS NOT NULL
GROUP BY s.id

我也试过了,结果一样

SELECT  
   s.student_name_first,
   s.student_name_last,
   (
   SELECT sum(i.points) AS points
   FROM incidents i
   WHERE i.student = s.id AND points IS NOT NULL 
   ) AS p
FROM students s
GROUP BY s.id

提前致谢


解决方案:

我一直在寻找的是HAVING

SELECT  
   s.student_name_first,
   s.student_name_last,
   (
   SELECT COALESCE(sum(i.incident_points),0)
   FROM incidents i
   WHERE i.student = s.id
   ) as points
FROM students s
GROUP BY s.id
HAVING points > 0
4

1 回答 1

2

问题是您不能SELECT在子句中使用别名WHERE,它们必须在HAVING.

但是,如果您使用内部联接,首先您不会得到任何空行。

SELECT s.student_name_first,
       s.student_name_last,
       SUM(i.points) AS points
FROM students s
JOIN incidents i
ON i.student = s.id
GROUP BY s.id
于 2013-07-16T05:39:48.670 回答