试图将查询放在phpMyAdmin中的另一个查询中

时间:2017-03-27 13:44:21

标签: mysql phpmyadmin

我正在尝试将查询用作来自另一个查询的数据源,但我不断从SELECT获得解析错误。我是SQL和phpmyadmin的新手,不知道为什么会出现这个错误。继承了我想要做的查询:

SELECT  CUS_CODE, 
 COUNT(LINE.INV_NUMBER) AS "Number of Invoices", 
 AVG("Invoice Total") AS "Average Invoice Amount", 
 MAX("Invoice Total") AS "Max Invoice Amount", 
 MIN("Invoice Total") AS "Min Invoice Amount", 
 Sum("Invoice Total") AS "Total Customer Purchases"
FROM    (SELECT CUS_CODE, LINE.INV_NUMBER AS INV_NUMBER,
        Sum(LINE.LINE_UNITS*LINE.LINE_PRICE) AS "Invoice Total"
        FROM    INVOICE, LINE 
        WHERE   INVOICE.INV_NUMBER = LINE.INV_NUMBER
        GROUP BY    CUS_CODE, LINE.INV_NUMBER)
GROUP BY    CUS_CODE;

很抱歉,如果我的问题不明确,但我可以回答任何问题以帮助解决问题。

1 个答案:

答案 0 :(得分:0)

您的查询:

SELECT CUS_CODE,
    COUNT(LINE.INV_NUMBER) AS "Number of Invoices",
    AVG("Invoice Total") AS "Average Invoice Amount",
    MAX("Invoice Total") AS "Max Invoice Amount",
    MIN("Invoice Total") AS "Min Invoice Amount",
    Sum("Invoice Total") AS "Total Customer Purchases"
FROM (
    SELECT CUS_CODE,
        LINE.INV_NUMBER,
        Sum(LINE.LINE_UNITS * LINE.LINE_PRICE) AS "Invoice Total"
    FROM INVOICE,
        LINE
    WHERE INVOICE.INV_NUMBER = LINE.INV_NUMBER
    GROUP BY CUS_CODE, INV_NUMBER
    )
GROUP BY CUS_CODE;

这里有几个问题:

  1. 在您的外部查询中,您引用了LINE.INV_NUMBER,但LINE表在此上下文中不可用。它是您想要的子查询的INV_NUMBER
  2. 您的子查询缺少别名,因此您无法在外部查询中引用它。这只会抛出没有别名的错误。
  3. 修正:

    SELECT t1.CUS_CODE,
        COUNT(t1.INV_NUMBER) AS "Number of Invoices",
        AVG(t1."Invoice Total") AS "Average Invoice Amount",
        MAX(t1."Invoice Total") AS "Max Invoice Amount",
        MIN(t1."Invoice Total") AS "Min Invoice Amount",
        Sum(t1."Invoice Total") AS "Total Customer Purchases"
    FROM (
        SELECT CUS_CODE,
            LINE.INV_NUMBER AS INV_NUMBER,
            Sum(LINE.LINE_UNITS * LINE.LINE_PRICE) AS "Invoice Total"
        FROM INVOICE,
            LINE
        WHERE INVOICE.INV_NUMBER = LINE.INV_NUMBER
        GROUP BY CUS_CODE,
            LINE.INV_NUMBER
        ) as t1
    GROUP BY CUS_CODE;