如何在SQL中对订单项进行计数

时间:2018-08-09 00:58:53

标签: sql sql-server

如何修改以下语法,使其仅计算和汇总ItemPrice值大于400的订单项。

USE Shop;


SELECT
    c.EmailAddress,
    COUNT(o.OrderID) AS OrderCount,
    SUM((i.DiscountAmount-i.ItemPrice) * i.Quantity) AS TotalOrderAmount
FROM Customers AS c 
JOIN Orders AS o ON c.CustomerID = o.CustomerID
JOIN OrderItems AS i ON o.OrderID = i.OrderID
GROUP BY c.EmailAddress
HAVING COUNT(c.EmailAddress) > 1
ORDER BY TotalOrderAmount DESC;

2 个答案:

答案 0 :(得分:1)

使用WHERE子句过滤掉行:

SELECT
    c.EmailAddress,
    COUNT(o.OrderID) AS OrderCount,
    SUM((i.DiscountAmount-i.ItemPrice) * i.Quantity) AS TotalOrderAmount
  FROM Customers AS c 
  JOIN Orders AS o ON c.CustomerID = o.CustomerID
  JOIN OrderItems AS i ON o.OrderID = i.OrderID
  WHERE i.ItemPrice > 400 -- Added a filtering condition here
  GROUP BY c.EmailAddress
  HAVING COUNT(c.EmailAddress) > 1
  ORDER BY TotalOrderAmount DESC;

答案 1 :(得分:0)

  • WHERE子句用于过滤记录。
  • WHERE子句仅用于提取满足以下条件的记录: 指定条件

因此,您需要一个where子句进行过滤,只需在加入后使用where子句

Where ItemPrice > 400