0

#1111 - Invalid use of group function由于 IF 循环中嵌入了两个 SUM() 调用,以下查询失败并抱怨 。到目前为止,我正在尝试在迁移到另一个 SQL 查询时完成相同的目标,但我遇到了困难,有人能指出我正确的方向吗?

数据库由一个表组成,如果客户没有立即支付发票,而是通过分期付款invoices,可能会有一些表。invoices_payments知道这一点,我试图总结所有 invoices.invoice_total 减去每个 invoices_payments.payment_date 不等于当前周仅当 invoices.issued_date 等于当前周,如果不是,那么我试图总结所有 invoices_payments.payment_amount 其中 invoices_payments .payment_date 等于当前周。

SELECT
    SUM(

        IF (
            YEARWEEK(i.issue_date, 1) = YEARWEEK(NOW(), 1),
            i.invoice_total,
            0
        )
    ) AS week_invoiced,
    ##SUM Functions embedded inside the next IF are causing error: #1111 - Invalid use of group function
    SUM(

        IF (
            ## If payment is issued on current week
            i.issued_date IS NOT NULL
            AND YEARWEEK(i.issued_date, '%Y%m') = YEARWEEK(NOW(), '%Y%m'),
            ## Sum each invoice.invoice_total and substract each invoices_payments not issued on current week
            SUM(i.invoice_total) - SUM(

                IF (
                    ip.id IS NOT NULL
                    AND YEARWEEK(ip.payment_date, 1) != YEARWEEK(NOW(), 1),
                    ip.payment_amount,
                    0
                )
            ),

        IF (
            ## If payment is not issued on current week
            i.issued_date IS NULL
            OR (
                i.issued_date IS NOT NULL
                AND YEARWEEK(i.issued_date, '%Y%m') != YEARWEEK(NOW(), '%Y%m')
            ),
            ## Sum each invoices_payments issued on current week
            SUM(

                IF (
                    ip.id IS NOT NULL
                    AND YEARWEEK(ip.payment_date, 1) = YEARWEEK(NOW(), 1),
                    ip.payment_amount,
                    0
                )
            ),
            0
        )
        )
    ) AS week_paid,
    SUM(

        IF (
            DATE_FORMAT(i.issue_date, '%Y%m') = DATE_FORMAT(NOW(), '%Y%m'),
            i.invoice_total,
            0
        )
    ) AS month_invoiced
FROM
    `invoices` AS i
INNER JOIN `currency` AS cur ON i.currency_id = cur.id
LEFT JOIN `invoices_payments` AS ip ON ip.invoice_id = i.id
WHERE
    i.coach_id = 279
AND (
    DATE_FORMAT(i.issue_date, '%Y%m') = DATE_FORMAT(NOW(), '%Y%m')
    OR DATE_FORMAT(i.issued_date, '%Y%m') = DATE_FORMAT(NOW(), '%Y%m')
    OR (
        ip.id IS NOT NULL
        AND DATE_FORMAT(ip.payment_date, '%Y%m') = DATE_FORMAT(NOW(), '%Y%m')
    )
)
GROUP BY
    i.id
4

1 回答 1

0

您不需要SUM问题所在的外部。也就是说,内部 SUM 就足够了:

SUM( SUM()-SUM() )

-->

SUM()-SUM()
于 2015-04-22T19:39:47.437 回答