执行SUM时SQL连接查询不起作用

时间:2016-05-31 03:39:17

标签: sql sql-server join sql-server-2014

我在SQL中有两个名为var categoriesToSort = []; //categoriesToSort has some values var sortedCategories = new Map(); for(var j = 0 ; j < categoriesToSort.length ; j++) { categories.forEachMap(function(key, value){ if(categoriesToSort[j] === value) { sortedCategories.set(key, value); } }); } tblFolding的表。在tblStockManagement我有tblFoldingFoldingID列。在Price我有tblStockManagement(来自FoldingID的外键)和tblFolding

我想要的是计算Quantity中可用的项目数量的Total Price,但tblStockManagement来自Price表。我正在尝试这个,但我不知道确切的查询。请帮助我。

2 个答案:

答案 0 :(得分:3)

这可能会有所帮助..

SELECT sum (b.Quantity*a.Price) as total price 
FROM tblFolding a, tblStockManagement b 
WHERE a.FoldingID = b.FoldingID 

答案 1 :(得分:1)

这将通过折叠ID提供总价格

SELECT TF.FoldingID, SUM(TF.Price * SM.Quantity) AS TotalPrice
FROM tblFolding TF
INNER JOIN tblStockManagement SM ON SM.FoldingID = TF.FoldingID
GROUP BY TF.FoldingID

如果不希望通过折叠得到结果并期望整个总价,请尝试:

SELECT SUM(TF.Price * SM.Quantity) AS TotalPrice
FROM tblFolding TF
INNER JOIN tblStockManagement SM ON SM.FoldingID = TF.FoldingID

<强>更新

根据您的评论,我了解您希望根据FoldingID表格中的tblStockManagement获得结果。所以添加WHERE子句并按条件过滤。

SELECT TF.FoldingID, SUM(TF.Price * SM.Quantity) AS TotalPrice
FROM tblFolding TF
INNER JOIN tblStockManagement SM ON SM.FoldingID = TF.FoldingID
WHERE SM.FoldingID IN (1, 2, 3, 4) -- modify the condition as per your requirement
GROUP BY TF.FoldingID