1

我有如下的mysql查询:

SELECT
  company_name,
  SUM(purchase_qty * num_of_certificate) AS total_purchase_qty,
  total_sold_qty,
  (total_purchase_qty - total_sold_qty) AS rem_qty
FROM tbl_company
  JOIN tbl_share_purchase
ON purchase_company_id = tbl_company.id
  JOIN (SELECT
      sold_company_id,
      SUM(sold_qty)   AS total_sold_qty
    FROM tbl_share_sales
    GROUP BY sold_company_id) s
ON s.sold_company_id = tbl_company.id
GROUP BY purchase_company_id

是否可以使用(total_purchase_qty - total_sold_qty) AS rem_qty来获取剩余数量?

4

1 回答 1

4

如果将其包装在子查询上,则可以这样做,但是如果别名定义在同一级别,则不能使用别名进行计算,

SELECT  company_name,
        SUM(purchase_qty * num_of_certificate) AS total_purchase_qty,
        total_sold_qty,
        (SUM(purchase_qty * num_of_certificate) - total_sold_qty) AS rem_qty
FROM    tbl_company
        JOIN tbl_share_purchase
            ON purchase_company_id = tbl_company.id
        JOIN 
        (
            SELECT  sold_company_id,
                    SUM(sold_qty)   AS total_sold_qty
            FROM    tbl_share_sales
            GROUP   BY sold_company_id
        ) s ON s.sold_company_id = tbl_company.id
GROUP   BY purchase_company_id

这里使用子查询,

SELECT  company_name,
        total_purchase_qty,
        total_sold_qty,
        (total_purchase_qty - total_sold_qty) AS rem_qty
FROM
(
    SELECT  company_name,
            SUM(purchase_qty * num_of_certificate) AS total_purchase_qty,
            total_sold_qty
    FROM    tbl_company
            JOIN tbl_share_purchase
                ON purchase_company_id = tbl_company.id
            JOIN 
            (
                SELECT  sold_company_id,
                        SUM(sold_qty)   AS total_sold_qty
                FROM    tbl_share_sales
                GROUP   BY sold_company_id
            ) s ON s.sold_company_id = tbl_company.id
    GROUP   BY purchase_company_id
) 
于 2013-03-04T03:10:43.283 回答