如何从单个表中查找订单大于X的客户

时间:2014-01-03 18:37:34

标签: mysql sql

如何在单个表格中找到订单金额超过2000美元的客户名称?

Customer : 
custName custOrderVal
A        100 
B        200
A        900
C        2400
A        1100
B        8000

select cust.custName from customer cust where cust.custOrderVal > 2000;不会显示正确的数据。有人可以指导我吗?

4 个答案:

答案 0 :(得分:2)

使用HAVING子句,如下所示:

SELECT custName
FROM Customer
GROUP BY custName
HAVING SUM(custOrderVal) > 2000

您需要使用GROUP BY为每个客户获取SUM,然后使用HAVING来限制结果(就像WHERE子句一样)。

答案 1 :(得分:2)

<强>查询

DECLARE @t TABLE (custName VARCHAR(10),custOrderVal INT)
INSERT INTO @t
VALUES
('A',100), ('B',200),('A',900),('C',2400),
('A',1100),('B',8000),('D',1000),('F',500)

SELECT  CustName
FROM @t
GROUP BY CustName
HAVING SUM(custOrderVal) > 2000

结果集

╔══════════╗
║ CustName ║
╠══════════╣
║ A        ║
║ B        ║
║ C        ║
╚══════════╝

答案 2 :(得分:2)

SELECT
  custName,
  SUM(custOrderVal) AS custOrderSum
FROM Customer
GROUP BY custName
HAVING custOrderSum>2000

答案 3 :(得分:0)

每当您需要过滤Grouped Totals时,都使用HAVING子句。

SELECT custName
FROM Customer
GROUP BY custName
HAVING SUM(custOrderVal) > 2000