2016-06-10 133 views
1

我在處理SQL查詢時遇到困難。我使用PostgreSQL。無法解決此SQL查詢

該查詢顯示:顯示已完成包含來自3個不同類別產品的訂單的客戶。結果將是2列,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; 

以下是查詢所需的數據庫表:

enter image description here

enter image description here

+0

你得到一個錯誤? – Matt

+0

不,但根據記錄給出的輸出是不合邏輯 – georgia

+0

http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when問題/ 285557#285557 –

回答

0
where SalesOrderDetail.SalesOrderDetailID in 
      (select DISTINCT count(ProductCategoryID) 

永遠不會給你一個結果作爲ID(SalesOrderDetailID)永遠邏輯上匹配COUNTcount(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 
+0

我執行它,我看了一下數據(數據庫中有太多記錄)我認爲輸出不正確 – georgia

+0

另外一些行中的輸出提供了55個產品類別在給出的數據中只有37個 – georgia

0

試試這個:

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