我有一个包含以下对象的数据库:
我正在尝试返回至少5个不同客户订购的产品名称。我的代码是:
SELECT Product.name, COUNT(DISTINCT custId) as cust_count
FROM Product P
INNER JOIN PO
ON PO.prodId = P.prodId
INNER JOIN "Order" O
ON O.orderId = PO.orderId
INNER JOIN Customer C
ON C.custId = O.custId
HAVING COUNT(DISTINCT custId) > 4;
我遇到以下错误:
无法绑定多部分标识符“ Product.name””列名“ custID”不明确
答案 0 :(得分:2)
您需要一个GROUP BY
并使用表别名:
SELECT p.name, COUNT(DISTINCT o.custId) as cust_count
FROM Product P INNER JOIN
PO
ON PO.prodId = P.prodId INNER JOIN
"Order" O
ON O.orderId = PO.orderId
GROUP BY p.name
HAVING COUNT(DISTINCT o.custId) > 4;
请注意,{id}位于JOIN
表中,因此不需要Customer
至Order
。
答案 1 :(得分:0)
您也可以尝试此方法。希望这可以解决您的问题
SELECT DISTINCT TOP(5)o.custId,p.name 从订单O INNER JOIN PO ON PO.orderID = O.orderID内部联接 产品P 开启P.prodID = PO.prodID