gpt4 book ai didi

mysql - 如何在 MySQL SUM 子查询中创建可用的别名

转载 作者:行者123 更新时间:2023-11-29 03:55:41 28 4
gpt4 key购买 nike

在下面的 MySQL 查询中,我能够生成一个 Sum 值,但无法分配一个可用于在 PHP 页面中回显的值。

SELECT
invoices.InvoiceNo AS Invoice,
invoices.invDate AS DATE,
invoices.invValue AS Amount,
(
SELECT SUM(invoices.invValue) AS GrandTotal
FROM invoices
WHERE invoices.fKey = 186 AND inv_openClosed = 0
)
FROM invoices
WHERE invoices.fKey = 186 AND inv_openClosed = 0
ORDER BY Invoice DESC

测试显示结果,但“GrandTotal”的别名不起作用。并且MySQL没有报错继续求解。

查询结果如下: enter image description here

最佳答案

别名需要在外部查询中而不是内部查询:

SELECT i.InvoiceNo AS Invoice,
i.invDate AS DATE,
i.invValue AS Amount,
(SELECT SUM(i2.invValue)
FROM invoices i2
WHERE i2.fKey = 186 AND i2.inv_openClosed = 0
) AS GrandTotal
FROM invoices i
WHERE i.fKey = 186 AND i.inv_openClosed = 0
ORDER BY i.Invoice DESC;

您会注意到我还包含了表别名和限定的列名。你也可以把它写成一个相关的子查询,所以你不需要重复常量:

       (SELECT SUM(i2.invValue)
FROM invoices i2
WHERE i2.fKey = i.fKey AND i2.inv_openClosed = i.inv_openClosed
) AS GrandTotal

而在 MySQL 8+ 中,您可以使用窗口函数:

SELECT i.InvoiceNo AS Invoice,
i.invDate AS DATE,
i.invValue AS Amount,
SUM(i.invValue) OVER (PARTITION BY fKey, inv_openClosed) as GrandTotal
FROM invoices i
WHERE i.fKey = 186 AND i.inv_openClosed = 0
ORDER BY i.Invoice DESC;

关于mysql - 如何在 MySQL SUM 子查询中创建可用的别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54190900/

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