以下查询失败并抱怨#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
答案 0 :(得分:0)
您不需要问题所在的外部SUM
。也就是说,内部SUMs就足够了:
SUM( SUM()-SUM() )
- >
SUM()-SUM()