显示内部联接表的总和,排除NULL总和

时间:2016-09-17 10:37:22

标签: sql oracle

SELECT 
t1.aID, t1.firstname, t1.lastname,
SUM(t2.price) AS sumsales
FROM t3
  INNER JOIN t1
    ON t3.aID = t1.aID
  INNER JOIN t2
    ON t3.wID = t2.wID
GROUP BY (t1.aID, t1.firstname, t1.lastname)
ORDER BY sumsales DESC

如何从此oracle SQL查询的结果中删除带有null sumsales列的所有行?

我试过

WHERE sumsales IS NOT NULL
上面的 GROUP BY ,但它不起作用。

用0替换null也是可以接受的,但我无法弄清楚如何在选择期间/之后替换null。

感谢您的时间。

2 个答案:

答案 0 :(得分:3)

由于sumsales是聚合值,因此您应使用having子句:

SELECT 
t1.aID, t1.firstname, t1.lastname,
SUM(t2.price) AS sumsales
FROM t3
  INNER JOIN t1
    ON t3.aID = t1.aID
  INNER JOIN t2
    ON t3.wID = t2.wID
GROUP BY (t1.aID, t1.firstname, t1.lastname)
HAVING sumsales IS NOT NULL
ORDER BY sumsales DESC

答案 1 :(得分:1)

您可以使用NULL0值替换为coalesce()

SELECT t1.aID, t1.firstname, t1.lastname,
       COALESCE(SUM(t2.price), 0) AS sumsales
FROM t3 INNER JOIN
     t1
     ON t3.aID = t1.aID INNER JOIN
     t2
     ON t3.wID = t2.wID
GROUP BY t1.aID, t1.firstname, t1.lastname
ORDER BY sumsales DESC;

或者,如果您不想NULL的{​​{1}}值,则可以在聚合之前过滤掉sumsales价格

NULL

这通常是最有效的方法。请注意,您不能在SELECT t1.aID, t1.firstname, t1.lastname, SUM(t2.price AS sumsales FROM t3 INNER JOIN t1 ON t3.aID = t1.aID INNER JOIN t2 ON t3.wID = t2.wID WHERE t2.price IS NOT NULL GROUP BY t1.aID, t1.firstname, t1.lastname ORDER BY sumsales DESC; 子句中使用聚合函数,但可以将它们放在WHERE子句中,如@NirLevy建议的那样。

除非您仅将其用于过滤目的,否则还不清楚HAVING的加入是什么。代码未使用该表中的任何列。