SQL /微软Access
我想弄清楚这个问题,但它已经花了我几天,我似乎无法解决它。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
就在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 - 访问可能对通配符有一些限制。更新。现在请尝试 – GurV
它已经工作了!非常感谢,这实际上是我一直在努力的最后一个问题! –
试试这个:
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
的非聚合列。
谢谢你的纠正! –