Postgresql Can';无法解决此SQL查询

Postgresql Can';无法解决此SQL查询,postgresql,Postgresql,我很难处理SQL查询。我使用PostgreSQL 查询显示:显示至少完成了包含3个不同类别产品的订单的客户。结果将是两列,CustomerID,以及订单数量。我已经写了这段代码,但我认为它不正确 select SalesOrderHeader.CustomerID, count(SalesOrderHeader.SalesOrderID) AS amount_of_orders from SalesOrderHeader inner join SalesOrderDetail o

我很难处理SQL查询。我使用PostgreSQL

查询显示:显示至少完成了包含3个不同类别产品的订单的客户。结果将是两列,
CustomerID
,以及订单数量。我已经写了这段代码,但我认为它不正确

select SalesOrderHeader.CustomerID,
       count(SalesOrderHeader.SalesOrderID) AS amount_of_orders
from SalesOrderHeader 
inner join SalesOrderDetail on
       (SalesOrderHeader.SalesOrderID=SalesOrderDetail.SalesOrderID)
inner join Product on 
       (SalesOrderDetail.ProductID=Product.ProductID)

where SalesOrderDetail.SalesOrderDetailID in 
       (select DISTINCT count(ProductCategoryID)
        from Product
        group by ProductCategoryID
        having count(DISTINCT ProductCategoryID)>=3)

group by SalesOrderHeader.CustomerID;
以下是查询所需的数据库表:

永远不会给您一个结果,因为ID(
SalesOrderDetailID
)在逻辑上永远不会匹配
计数(
COUNT(ProductCategoryID)

这会让你得到我认为你想要的输出

SELECT soh.CustomerID, COUNT(soh.SalesOrderID) AS amount_of_orders
FROM SalesOrderHeader soh
INNER JOIN SalesOrderDetail sod ON soh.SalesOrderID = sod.SalesOrderID
INNER JOIN Product p ON sod.ProductID = p.ProductID
HAVING COUNT(DISTINCT p.ProductCategoryID) >= 3
GROUP BY soh.CustomerID
永远不会给您一个结果,因为ID(
SalesOrderDetailID
)在逻辑上永远不会匹配
计数(
COUNT(ProductCategoryID)

这会让你得到我认为你想要的输出

SELECT soh.CustomerID, COUNT(soh.SalesOrderID) AS amount_of_orders
FROM SalesOrderHeader soh
INNER JOIN SalesOrderDetail sod ON soh.SalesOrderID = sod.SalesOrderID
INNER JOIN Product p ON sod.ProductID = p.ProductID
HAVING COUNT(DISTINCT p.ProductCategoryID) >= 3
GROUP BY soh.CustomerID
试试这个:

select CustomerID,count(*) as amount_of_order from 
  SalesOrder join 
 (
   select SalesOrderID,count(distinct ProductCategoryID) CategoryCount 
     from SalesOrderDetail JOIN Product using (ProductId)
  group by 1
 ) CatCount using (SalesOrderId) 
 group by 1 
 having bool_or(CategoryCount>=3) -- At least on CategoryCount>=3
试试这个:

select CustomerID,count(*) as amount_of_order from 
  SalesOrder join 
 (
   select SalesOrderID,count(distinct ProductCategoryID) CategoryCount 
     from SalesOrderDetail JOIN Product using (ProductId)
  group by 1
 ) CatCount using (SalesOrderId) 
 group by 1 
 having bool_or(CategoryCount>=3) -- At least on CategoryCount>=3

你有错误吗?没有,但是根据给定的记录,输出不符合逻辑吗?没有,但是根据给定的记录,输出不符合逻辑。我执行它,我查看了数据(数据库中的记录太多)我认为输出不正确当数据中只有37个时,某些行的输出给出55个产品类别我执行它,我查看了数据(数据库中有太多记录),我认为输出不正确当数据中只有37个时,某些行的输出给出55个产品类别