我在derby数据库中有两个表,我想一起查询。
Orders
+----+--------+--------------+------------+
| ID | UserID | PurchaseDate | TotalPrice |
+----+--------+--------------+------------+
| 1 | 1 | TIMESTAMP | 7.00 |
OrderItems
+---------+-----------+----------+
| OrderID | ProductID | Quantity |
+---------+-----------+----------+
| 1 | 1 | 2 |
我想查询从订单表中返回订单上的所有信息以及与该订单关联的产品总数。
我试过这个认为它会起作用但得到错误 - "列参考' 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
答案 0 :(得分:9)
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
答案 1 :(得分:0)
我认为你需要一个group by子句,如:
GROUP BY orders.ID,orders.UserID,orders.PurchaseDate,orders.TotalPrice