我已经在下面添加了两个我要加入的SQL语句,它们都分别完美地运行,但是当我们尝试加入它们时,我没有得到我想要的结果。我将解释我使用的3个表,并将代码放在下面。
有3个表 stoctran ,库存和部门。让我们从部门开始,它包含一个部门和一个描述(例如:01,' Food')。然后是 stock 表,其中包含代码,描述,部门(代码),onhand(sotre中的项目数)和avrgcost(产品的平均成本)。然后最后有 stoctran 这个表格中包含每个产品的每个销售,字段如下:itemcode(与库存相同),tcode(区分发票和信用卡的代码) note),金额(该项目的金额),成本(该项目的成本),部门(项目所在的部门)和txdate(产品销售日期)。
正如您在下面的代码中看到的,我的第一个SQL语句计算特定日期(' 2017-01-01'和当前日期)之间的nettsales和nettcost,并将其分组为部门和用途department表提供旁边部门的描述。然后第二个SQL语句用(onhand * avrgcost)计算总库存值并将其分组到一个部门,这些部门也使用department表在列中添加它的描述。
现在我的问题是如何以一种方式加入这两个SQL语句,这些方法为第一个语句中的所有列提供了包含每个部门的总库存值的附加列。所以基本上取第二个语句的第二列并将其添加到第一个语句列。
每个部门的净销售额和净成本(第一)
SELECT
a.DEPARTMENT,
b.DESCRIPTIO,
ROUND(SUM(IF(a.TCODE = 'IN', a.AMOUNT, 0)) -
SUM(IF(a.TCODE = 'CN', a.AMOUNT, 0)), 2) As NettSales,
ROUND(Sum(If(a.TCODE = 'IN', a.COST, 0)) - Sum(If(a.TCODE = 'CN', a.COST, 0)) As NettCost
FROM
stoctran a
LEFT JOIN
department b ON a.DEPARTMENT = b.DEPARTMENT
WHERE
a.TXDATE BETWEEN ;2017-01-01' And current_date
GROUP BY
a.DEPARTMENT
股票持有每个部门(第二个)
SELECT
a.DEPARTMENT,
SUM(a.AVRGCOST * a.ONHAND) As StockValue
FROM
stock a
LEFT JOIN
department b On a.DEPARTMENT = b.DEPARTMENT
GROUP BY
a.DEPARTMENT
答案 0 :(得分:0)
select net.*, stock.StockValue
from (SELECT a.DEPARTMENT,
b.DESCRIPTIO,
ROUND(SUM(IF(a.TCODE = 'IN', a.AMOUNT, 0)) -
SUM(IF(a.TCODE = 'CN', a.AMOUNT, 0)), 2) As NettSales,
ROUND(Sum(If(a.TCODE = 'IN', a.COST, 0)) - Sum(If(a.TCODE = 'CN', a.COST, 0)) As NettCost
FROM stoctran a
LEFT JOIN department b ON a.DEPARTMENT = b.DEPARTMENT
WHERE a.TXDATE BETWEEN '2017-01-01' And current_date
GROUP BY a.DEPARTMENT) net
join (SELECT a.DEPARTMENT,
SUM(a.AVRGCOST * a.ONHAND) As StockValue
FROM stock a
LEFT JOIN department b On a.DEPARTMENT = b.DEPARTMENT
GROUP BY a.DEPARTMENT) stock
on (stock.department=net.department)