如何减去作为子查询结果的2列

时间:2015-10-28 00:35:30

标签: mysql subquery subtraction

我有这个查询,它按预期工作正常,即它显示所有列以及每个子查询中的2列...

SELECT 
    a.group_id,
    a.code,
    a.description_en,
    c.size_code,
    (
        SELECT
            SUM(b.qty)
        FROM
            receiving_details AS b
        WHERE
            b.code = c.size_code
    ) AS in_qty,
    (
        SELECT
            SUM(d.qty)
        FROM
            requisition_details AS d
        WHERE
            d. matl_code = c.size_code
    ) AS out_qty
FROM products AS a
INNER JOIN products_sizes AS c ON c.prod_code = a.code
ORDER BY a.group_id ASC, a.code ASC, c.size_code ASC

然而,当我尝试添加此行...

(in_qty - out_qty) AS balance,

就在' FROM'之前声明,我收到未知列' in_qty'的错误在'字段列表'

我做错了什么?

修改

从接受的答案中,我做了一些修复,得到了我想要的结果。

SELECT *, (e.in_qty - e.out_qty) AS balance FROM
(SELECT 
    a.group_id,
    a.code,
    a.description_en,
    c.size_code,
    (
        SELECT
            IFNULL(SUM(b.qty),0)
        FROM
            receiving_details AS b
        WHERE
            b.code = c.size_code
    ) AS in_qty,
    (
        SELECT
            IFNULL(SUM(d.qty),0)
        FROM
            requisition_details AS d
        WHERE
            d. matl_code = c.size_code
    ) AS out_qty
FROM products AS a
INNER JOIN products_sizes AS c ON c.prod_code = a.code) AS e
ORDER BY e.group_id ASC, e.code ASC, e.size_code ASC

1 个答案:

答案 0 :(得分:1)

您无法在自己的select语句中引用相同的字段。一种选择是将结果移动到另一个子查询中,然后执行计算:

select *, (in_qty - out_qty) AS balance
from (
    SELECT 
        a.group_id,
        a.code,
        a.description_en,
        c.size_code,
        (
            SELECT
                SUM(b.qty)
            FROM
                receiving_details AS b
            WHERE
                b.code = c.size_code
        ) AS in_qty,
        (
            SELECT
                SUM(d.qty)
            FROM
                requisition_details AS d
            WHERE
                d. matl_code = c.size_code
        ) AS out_qty
    FROM products AS a
    INNER JOIN products_sizes AS c ON c.prod_code = a.code
) t
ORDER BY group_id, code, size_code