不同表之间的SQL计算

时间:2017-10-22 16:35:38

标签: sql oracle

我有3个表如下:

表1

BusinessId | CustomerName

表2

BusinessId | Product Name

表3

Product Name | Price 

我尝试编写一个查询,该查询应计算每个客户的总成本:

SELECT Table1.CustomerName, COUNT(Table2.Product Name) * Table3.Price
FROM Table1, Table2, Table3
WHERE Table1.BusinessId = Table2.BusinessId AND
Table2.Product Name = Table3.Product Name
GROUP BY SERVICE_NAME

但这不起作用:(

任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

从不FROM子句中使用逗号。 始终使用正确的JOIN语法。

以下内容应该更接近您的需求。它至少解决了查询中的一堆问题:

SELECT t1.CustomerName, SUM(t3.Price)  -- use the right aggregation function
FROM Table1 t1 JOIN
     Table2 t2
     ON t1.BusinessId = t2.BusinessId JOIN   -- column name spelled correctly
     Table3 t3
     ON t1.BusinessId = t2.BusinessId AND
        t2.ProductName = t3.ProductName  -- if the column has a space, you need to escape it
GROUP BY t1.CustomerName  -- aggregate by the right column

答案 1 :(得分:-1)

COUNT(表2.产品名称)

这里没有空位

您的查询可能看起来像

SELECT Table1.CustomerName, COUNT(Table2.ProductName) * Table3.Price
FROM Table1, Table2, Table3
WHERE Table1.BusinessId = Table2.BusinessId AND
Table2.ProductName = Table3.ProductName
GROUP BY Table1.CustomerName,Table3.Price