如何添加WHERE条件以使用INNER JOINs进行编码?

时间:2019-04-28 17:04:50

标签: sql sql-server inner-join where

我不知道如何为AS列添加where条件,

我尝试使用带方括号的列,但它不起作用

SELECT   
    Suppliers.CompanyName,
    SUM([Order Details].UnitPrice*Quantity) AS [Total sales]
FROM
    [Order Details]  
INNER JOIN 
    Products ON products.ProductID = [Order Details].ProductID
INNER JOIN 
    Suppliers ON Products.SupplierID = Suppliers.SupplierID
WHERE 

GROUP BY 
    Suppliers.CompanyName
ORDER BY 
    2 DESC;

我只希望看到总销售额超过10,000

2 个答案:

答案 0 :(得分:4)

您需要在HAVING子句中添加条件:

SELECT  
  Suppliers.CompanyName, 
  SUM([Order Details].UnitPrice*Quantity)AS [Total sales]
FROM [Order Details] 
INNER JOIN 
Products ON products.ProductID= [Order Details] .ProductID
INNER JOIN
Suppliers ON Products.SupplierID= Suppliers.SupplierID
GROUP BY Suppliers.CompanyName
HAVING SUM([Order Details].UnitPrice*Quantity) > 10000
Order by 2 desc;

答案 1 :(得分:2)

您只需要添加一个HAVING子句而不是一个WHERE子句,

GROUP BY之后

HAVING SUM([Order Details].UnitPrice*Quantity) > 10000

在您的SQL语句中:

SELECT  Suppliers.CompanyName, SUM([Order Details].UnitPrice*Quantity) AS [Total sales]    
  FROM [Order Details]     
 INNER JOIN 
        Products ON products.ProductID= [Order Details] .ProductID
 INNER JOIN
        Suppliers ON Products.SupplierID= Suppliers.SupplierID
GROUP BY Suppliers.CompanyName
HAVING SUM([Order Details].UnitPrice*Quantity) > 10000
ORDER BY 2 desc