SQL / Microsoft Access

时间:2017-02-15 05:39:05

标签: sql ms-access

我想弄清楚这个问题但是,它已经花了我几天时间,我似乎无法解决它。

问题要求:

显示产品列表(显示ProductID和ProductDescription作为前两列),每个产品的订购次数(第三列),以及每个产品在所有订单上的订购总量(第四列)列)。

数据库:

**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

2 个答案:

答案 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;

答案 1 :(得分: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给出的答案比这更简洁,适用于这个特定问题,但一般情况下你需要使用子查询从OrderLine-T表中获取统计数据,假设你想包含非-ggregate报告中Product_T的列。