我正在尝试基于W3Schools.com SQL数据库解决此问题。到目前为止,我想出了以下内容,其中显示了之前订购相同产品的客户的客户名称和产品。我在订购客户订购的相同产品的总数方面存在问题。
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 :(得分:1)
您已经拥有了客户的结果查询。将其移动到子查询并加入自身
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