我有3张桌子。
'Order details'
OrderID | Quantity | UnitPrice | ProductID
1002 | 19 | 17 | 824
1003 | 5 | 15 | 285
1004 | 7 | 6 | 543
'Orders'
OrderID | CustomerID
1002 | 224
1003 | 224
1004 | 348
'Customers'
CustomerID| Name | Phone
224 | John | 235-453
225 | July | 532-232
我必须获得有关订购超过10种产品且平均价格低于17的人的信息。我这样做了,但我不确定这是否是最佳方法。
SELECT *
FROM customers
WHERE customerid IN
(SELECT DISTINCT customerid
FROM orders
WHERE orderid IN
(SELECT orderid id
FROM 'order details'
WHERE 17 >
(SELECT avg(unitprice)
FROM 'order details'
WHERE orderid = id
GROUP BY orderid)
AND 10 <
(SELECT sum(quantity)
FROM 'order details'
WHERE orderid = id
GROUP BY orderid)
GROUP BY orderid))
答案 0 :(得分:0)
您可以使用"having" clause过滤聚合(总和,计数等)符合特定条件的记录。
这将是:
select customer.Name,
count(*),
avg(od.unitPrice)
from customers c
inner join orders o on c.customerID = o.customerID
inner join orderDetails od on o.orderID = od.orderID
group by customer.Name
having count(*) > 10
and avg(od.unitPrice) < 17
答案 1 :(得分:0)
尝试这个,不确定它是否可以作为避风港检查过。
SELECT
avg(od.unitPrice) AS AVGunitPrice,
c.Name,
c.Phone
FROM Customer c
INNER JOIN Orders o ON o.customerID = c.CustomerID
INNER JOIN OrderDetail od ON od.OrderID = o.OrderId
WHERE od.Quantity > 10
GROUP BY c.Name, c.Phone
HAVING avg(od.unitPrice) < 17