2017-11-04 17 views
0

W3Schools.com SQLデータベースに基づいてこの問題を解決しようとしています。これまでは、同じ商品を以前に注文した顧客の顧客名と商品IDを表示する次のものを用意しました。私は、顧客が注文した同一の製品を注文する総数を含めることに問題があります。以前同じ商品を注文した顧客の場合、同一の商品を注文した顧客名、商品ID、合計注文数を表示します。

select customername, products.productid, productname 
from orderdetails, orders, customers, products 
where orderdetails.orderid=orders.orderid AND 
     orders.customerid=customers.customerid AND 
     orderdetails.productid=products.productid 
group by customername, products.productid, productname 
HAVING COUNT(*) > 1 
order by customername; 

答えて

0

お客様にはすでに結果クエリがあります。サブクエリに移動してそれ自身に参加する

SELECT * 
FROM 
    (select customername, products.productid, productname, COUNT(*) as cnt 
    from orderdetails, orders, customers, products 
    where orderdetails.orderid=orders.orderid AND 
      orders.customerid=customers.customerid AND 
      orderdetails.productid=products.productid 
    group by customername, products.productid, productname 
    HAVING COUNT(*) > 1) c1 
    INNER JOIN 
    (select customername, products.productid, productname, COUNT(*) as cnt 
     from orderdetails, orders, customers, products 
     where orderdetails.orderid=orders.orderid AND 
      orders.customerid=customers.customerid AND 
      orderdetails.productid=products.productid 
     group by customername, products.productid, productname 
     HAVING COUNT(*) > 1) c2 
    ON c1.productId=c2.productId and c1.productname=c2.productname 

order by c1.customername