SELECT语句没有结果

Cam*_*ole 1 mysql sql select

以下SELECT语句产生此结果

SELECT ProductID, SUM(Quantity) AS Quantity
FROM Production.ProductInventory
WHERE ProductID NOT IN (1001)
GROUP BY ProductID;
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

为什么下面编辑的SELECT语句不会产生任何结果?

SELECT ProductID, SUM(Quantity) AS Quantity
FROM Production.ProductInventory
WHERE Quantity >= 1800
GROUP BY ProductID;
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Luk*_*zda 6

你添加了WHERE条款:

SELECT ProductID, SUM(Quantity) AS Quantity
FROM Production.ProductInventory
WHERE Quantity >= 1800  -- no single row with Quantity that is higher than 1800
GROUP BY ProductID;
Run Code Online (Sandbox Code Playgroud)

您可能希望在聚合后过滤值:

SELECT ProductID, SUM(Quantity) AS Quantity
FROM Production.ProductInventory
GROUP BY ProductID
HAVING SUM(Quantity) >= 1800;   -- HAVING instead of WHERE
Run Code Online (Sandbox Code Playgroud)

过滤:

  • 在哪里 - 聚合之前
  • HAVING - 聚合后