所以我试图找出每个客户在削减和产品上花费的总金额
我不知道我的查询是错的还是我的整个数据库架构有什么想法?
我的查询
`Select First_Name, SUM(B.Cost), SUM(C.Cost)
FROM bookings A, cuts B, products C, customers D
Where A.Customer_ID= D.Customer_ID
AND A.Cut_ID = B.Cut_ID
AND A.Product_ID= C.Product_ID;`
我的数据库
`Table: bookings
Booking_N0, Customer_ID, Cut_ID, Product_ID, TimeTaken`
`Table: customers
Customre_ID, First_Name, Sex`
`Table: products
Product_ID, Products, Cost`
`Table: cuts
Cut_ID, Cut, Cost`
答案 0 :(得分:1)
每个客户都应该GROUP BY
到SUM
:
Select D.First_Name
, SUM(B.Cost)
, SUM(C.Cost)
FROM bookings A LEFT JOIN cuts B ON A.Cut_ID = B.Cut_ID
JOIN products C ON A.Product_ID = C.Product_ID
JOIN customers D ON A.Customer_ID = D.Customer_ID
GROUP BY D.First_Name;
此外,期待使用显式连接表示法(FROM table1 t1 JOIN table2 t2 ON t1.field1 = t2.field2
)而不是隐式连接表示法(FROM table1 t1, table2 t2 WHERE t1.field1 = t2.field2
),因为它有更多直观视图(表格列在它们加入的条件附近)。
答案 1 :(得分:0)
开始使用推荐的JOIN / ON
语法进行连接,而不是使用WHERE
子句。您还需要GROUP BY
子句
Select First_Name, SUM(B.Cost), SUM(C.Cost)
FROM bookings A
INNER JOIN cuts B
ON A.Cut_ID = B.Cut_ID
INNER JOIN products C
ON A.Product_ID= C.Product_ID
INNER JOIN customers D
ON A.Customer_ID= D.Customer_ID
GROUP BY First_Name
答案 2 :(得分:0)
如果使用SUM等聚合函数,则必须添加group by子句 在你的情况下:
...
AND A.Product_ID= C.Product_ID
GROUP BY First_Name