6

我想一起查询 derby 数据库中有两个表。

Orders
+----+--------+--------------+------------+
| ID | UserID | PurchaseDate | TotalPrice |
+----+--------+--------------+------------+
|  1 |    1   | TIMESTAMP    |    7.00    |

OrderItems
+---------+-----------+----------+
| OrderID | ProductID | Quantity |
+---------+-----------+----------+
|    1    |      1    |     2    |

我想要一个查询来返回 Orders 表中有关订单的所有信息以及与该订单关联的产品总数。

我试过这个,以为它会起作用,但得到错误 - “列引用'ID'无效。当 SELECT 列表包含至少一个聚合时,所有条目都必须是有效的聚合表达式。”

SELECT 
orders.ID, orders.UserID, orders.PurchaseDate, orders.TotalPrice, SUM(Quantity) 
AS productCount
FROM app.orders JOIN app.orderItems ON orders.ID=orderItems.OrderID 
4

2 回答 2

11
SELECT 
app.orders.ID, app.orders.UserID, app.orders.PurchaseDate, app.orders.TotalPrice, SUM(app.orderItems.Quantity) 
AS productCount
FROM app.orders JOIN app.orderItems ON app.orders.ID=app.orderItems.OrderID 
group by app.orders.ID, app.orders.UserID, app.orders.PurchaseDate, app.orders.TotalPrice
于 2012-05-03T10:48:12.657 回答
0

我认为您需要一个 group by 子句,例如:

GROUP BY orders.ID,orders.UserID,orders.PurchaseDate,orders.TotalPrice
于 2012-05-03T10:34:15.053 回答