在MySQL中计算两个别名的值[已关闭]

xzlaal3s  于 2023-05-21  发布在  Mysql
关注(0)|答案(2)|浏览(251)

**关闭。**此题需要debugging details。目前不接受答复。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
4天前关闭。
Improve this question
如何计算这两个别名并在其他列中显示它们?

SELECT SUM(qty1) AS ali_qty1,
    (SELECT SUM(qty2) FROM table2 WHERE col2 = 'B') AS ali_qty2,
    (SELECT SUM(ali_qty1) - SUM(ali_qty2) as total_qty)
FROM table1
WHERE col1= 'A'

表1

ID | col1  | qty1
------------------
1  | A       | 50
2  | A       | 20

表2

ID | col2  | qty2
------------------
1  | B       | 50
2  | B       | 10

期望输出

ID | ali_qty1  | ali_qty2 | ali_qty3
-------------------------------------
1  |  70          | 60        | 10
uelo1irk

uelo1irk1#

SELECT ali_qty1, ali_qty2 , (ali_qty2 - ali_qty1) AS ali_qty3
FROM (
select
(select sum(qty1)   from table1 where col1='A')  as ali_qty1,
(select sum(qty2)   from table2 where col2='B') as ali_qty2
) T1
ef1yzkbh

ef1yzkbh2#

对于这个数据,我们可以交叉连接两个聚合查询,然后执行计算:

select t1.ali_qty1, t2.ali_qty2, t1.ali_qty1 - t2.ali_qty2 ali_qty3
from (select sum(qty1) ali_qty1 from table1 where col1 = 'A') t1
cross join (select sum(qty2) ali_qty2  from table2) t2

请注意,这始终返回一行-但是两个和中的任何一个都可能是null,在这种情况下,您可能希望在减法中使用coalesce()

相关问题