如何在单个表格中找到订单金额超过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;
不会显示正确的数据。有人可以指导我吗?
答案 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