我有一个“订单”表:
ID CustomerID Freight
1 VINET 32.38
2 TOMPS 11.61
. . .
. . .
. . .
我想只选择运费超过平均水平的那些customerID !!
SELECT CustomerID FROM Orders WHERE CustomerID IN(SELECT CustomerID,AVG(Freight) AVGFreight FROM Orders Group By CustomerID )
我知道到这里,但我怎么能比较运费和平均值呢?请帮助我谢谢
答案 0 :(得分:1)
我假设客户每人都有1条记录。
<击> SELECT CustomerID 来自dbo.Orders 运费&gt; =(SELECT @AvgFreight = AVG(运费)FROM dbo.Orders) 击>
我不确定,如果这样可行的话。试试吧。
Upvote @ marc_s的回答,因为我的回答是基于它。
SELECT CustomerID
FROM dbo.Orders
WHERE AVG(Freight) >= (SELECT AVG(Freight) FROM dbo.Orders)
GROUP BY CustomerID
答案 1 :(得分:0)
这个怎么样:
SELECT CustomerID
FROM dbo.Orders
WHERE Freight >= (SELECT AVG(Freight) FROM dbo.Orders)
GROUP BY CustomerID
您选择的客户,所有客户的运费都大于表中所有运费的平均值。
答案 2 :(得分:0)
CREATE TABLE Orders(
ID int,
CustomerId varchar(10),
Freight money
);
INSERT INTO Orders Values(1,'VINET',10);
INSERT INTO Orders values(2,'VINET',10);
INSERT INTO Orders values(3,'TOMPS',12);
INSERT INTO Orders values(4,'TOMPS',11);
显示平均值:
Select CustomerId,avg(Freight)AvgFreight
from Orders
group by customerId
| CustomerId | AvgFreight |
|------------+------------|
| TOMPS | 11.50 |
| VINET | 10.00 |
|------------+------------|
将运费与平均值进行比较:
Select Orders.CustomerId
from Orders,
(Select CustomerId,avg(Freight)AvgFreight
from Orders
Group by customerId)t
Where Orders.Freight > t.AvgFreight
And Orders.CustomerId = t.Customerid
| CustomerId |
|------------|
| TOMPS |
|------------|
答案 3 :(得分:0)
使用HAVING
子句。
SELECT CustomerID
FROM Orders
GROUP BY CustomerID
HAVING AVG(Freight) > (SELECT AVG(Freight) FROM Orders)