2

我在 PostgreSql 数据库中使用三个表:

Customer(Id, Name, City),
Product(Id, Name, Price),
Orders(Customer_Id, Product_Id, Date)

我想执行一个查询以从他们那里获得“已经订购了至少两种不同产品以及产品的客户”。我写的查询是:

select c.*, p.*
from customer c
join orders o on o.customer_id = c.id
join product p on p.id = o.product_id
group by (c.id)
having count(distinct o.product_id)>=2

它抛出错误:

“列“p.id”必须出现在 GROUP BY 子句中或用于聚合函数第 1 行:select c.*, p.*“。

但是,如果我从 select 语句中删除 p.* (假设我不想要产品,只想要客户),它运行正常。我怎样才能得到产品呢?

更新:订购了两种或多种产品后,客户在输出中出现的次数必须与他订购的产品一样多。我想要一个包含 5 列的表作为输出:

Cust ID | Cust Name | Cust City | Prod ID | Prod Name | Prod Price

鉴于group by应该使用的 SQL 是否有可能?应该在不同表的多个列上使用它吗?

4

2 回答 2

2

试试这个:

SELECT distinct c.* ,p.*
FROM Customer c
JOIN
   (SELECT o.customer_id cid
    FROM Product P
    JOIN Orders o
    ON p.id= o.product_id
    GROUP BY o.customer_id
    HAVING COUNT(distinct o.product_id)>=2) cp
ON c.id =cp.cid
JOIN Orders o
on c.id=o.customer_id
JOIN Product p
ON o.product_id =p.id

我希望它能解决你的问题。

于 2013-05-20T09:22:10.100 回答
1

我认为您可以对这个问题使用以下查询 -

SELECT C1.*, p1.*
  FROM Customer C1
  JOIN Orders O1 ON O1.Customer_Id = C1.Id
  JOIN Product P1 ON P1.Id = O1.Product_Id
 WHERE C1.Id IN (SELECT c.Id
                   FROM Customer c
                   JOIN Orders o ON o.Customer_Id = c.Id
                  GROUP BY (c.Id)
                 HAVING COUNT(DISTINCT o.Product_Id) >= 2)
于 2013-05-20T09:14:39.400 回答