【问题标题】:SQL/Microsoft AccessSQL/微软访问
【发布时间】:2017-02-15 05:39:04
【问题描述】:

我正在尝试解决这个问题,但是我已经花了几天时间,而且我似乎无法解决它。

问题要求:

显示产品列表(将 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

【问题讨论】:

  • 感谢指正!

标签: sql ms-access


【解决方案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;

【讨论】:

  • 我试过了,但出现“无法对使用 '*' (p) 选择的字段进行分组”的错误。
  • @DucLe - 访问可能对通配符有一些限制。更新。请立即尝试
  • 成功了!非常感谢,这实际上是我这几天一直在解决的最后一个问题!
【解决方案2】:

试试这个:

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 表中获取统计信息,假设你想包含非聚合报告中来自Product_T 的列。

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多