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

时间:2019-01-14 23:53:02

标签: mysql sql

在以下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

2 个答案:

答案 0 :(得分:5)

别名必须位于外部查询中,而不是内部查询中:

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;

答案 1 :(得分:3)

在子查询中使用别名代替其结果:

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