执行选择后,我收到错误"未知列'点'在' where子句'
如何从外部查询中删除包含从子查询返回的空记录的行? (我需要使用子查询,因为我需要运行另一组子查询来返回我之后的结果)
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
答案 0 :(得分: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