私は3つのテーブルを持っています:
お客様
ID_CUSTOMER
NAME
製品
ID_PRODUCT
PRODUCTNAME
PRICE
注文
ID_ORDER
CUSTOMER_ID
PRODUCT_ID
QUANTITY
10,000ドル以上で注文したすべての顧客を選択するにはどうすればよいですか?
select c.*
from customers c
inner join orders o on o.customer_id = c.id_customer
inner join products p on p.id_product = o.product_id
group by c.id_customer
having sum(p.price * o.quantity) >= 10000
これを試して:
SELECT a.ID_CUSTOMER,
a.NAME
FROM CUSTOMERS a
INNER JOIN ORDERS b
ON b.CUSTOMER_ID = a.ID_CUSTOMER
INNER JOIN PRODUCTS c
ON c.ID_PRODUCT = b.product_id
GROUP BY a.ID_CUSTOMER, a.NAME
HAVING SUM(c.PRICE * b.QUANTITY) >= 10000
次のようなものを試してください:
SELECT C.ID_CUSTOMER, C.Name,
SUM(P.PRICE * O.QUANTITY) AS Total FROM Customers C
JOIN Orders O ON C.CUSTOMER_ID = O.CUSTOMER_ID
JOIN Procucts P ON P.PRODUCT_ID = O.PRODUCT_ID
GROUP BY C.ID_CUSTOMER, C.Name
HAVING SUM(P.PRICE * O.QUANTITY) >= 10000
実際には複雑なクエリではありません。同じことを行う別の構文:
SELECT C.ID_CUSTOMER, C.NAME, SUM(P.PRICE * O.QUANTITY) TOTAL
FROM Products P, Customers C, Orders O
WHERE O.CUSTOMER_ID = C.ID_CUSTOMER
AND O.PRODUCT_ID = P.ID_PRODUCT
GROUP BY C.ID_CUSTOMER, C.NAME
HAVING SUM(P.PRICE * O.QUANTITY) >= 10000