2017-02-15 164 views
0

我想弄清楚這個問題,但它已經花了我幾天,我似乎無法解決它。SQL /微軟Access

的問題要求:

顯示的產品(顯示產品ID和產品描述的前兩列)的列表,每個產品已被責令次數(第三列),總數量的每個產品已經訂購了所有訂單(第四列)。

數據庫:

**Product_T**          **OrderLine_T** 
ProductID ProductDescription     ProductID OrderedQuantity 
1   End Table        1   2 
2   Coffe Table       2   2 
3   Computer Desk       4   1 
4   Entertainment Center     3   5 
5   Writers Desk       3   3 
6   8-Drawer Desk       6   2 
7   Dining Table       8   2 
8   Computer Desk       4   4 
               4   1 
               5   2 
               7   2 
               1   3 
               2   2 
               3   3 
               8   3 
               4   2 
               7   3 
               8   10 
+0

謝謝你的糾正! –

回答

1

就在JOIN和GROUP BY

SELECT p.ProductID, 
     p.ProductDescription, 
     COUNT(*) AS time_ordered, 
     SUM(o.OrderedQuantity) AS qty_ordered 
FROM Product_T as p 
LEFT JOIN OrderLine_T AS o 
    ON p.ProductID = o.ProductID 
GROUP BY p.ProductID, 
     p.ProductDescription; 
+0

我試過這個,但是它有一個錯誤:「無法對使用'*'(p)選擇的字段進行分組。 –

+0

@DucLe - 訪問可能對通配符有一些限制。更新。現在請嘗試 – GurV

+0

它已經工作了!非常感謝,這實際上是我一直在努力的最後一個問題! –

1

試試這個:

SELECT t1.ProductID, 
     t1.ProductDescription, 
     COALESCE(t2.num_times_ordered, 0) AS num_times_ordered, 
     COALESCE(t2.total_quantity, 0) AS total_quantity 
FROM Product_T t1 
LEFT JOIN 
(
    SELECT ProductID, 
      COUNT(*) AS num_times_ordered, 
      SUM(OrderedQuantity) AS total_quantity 
    FROM OrderLine-T 
    GROUP BY ProductID 
) t2 
    ON t1.ProductID = t2.ProductID 

通過@GurV給出的答案是比這和作品更簡潔對於這個特定的問題,但一般來說,你需要使用子查詢來獲得的統計信息10表,假設您想在報告中包含來自Product_T的非聚合列。