gpt4 book ai didi

mysql - 在mysql中使用虚拟列

转载 作者:搜寻专家 更新时间:2023-10-30 22:00:47 26 4
gpt4 key购买 nike

我有如下 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 来获取剩余数量?

最佳答案

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

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
)

关于mysql - 在mysql中使用虚拟列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15193972/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com