我有一个查询来计算表invoice
中的发票。此发票包含与tax_recv
表中相关的税费。 tax_recv
将有多行绑定到invoice
表格中的发票。
我有一个查询,可以计算12个月的发票,并按照相应的日期对其进行排序。这是查询:
SELECT
invoice_amount + late_fee + SUM(c.tax) AS amount, tollfree_json, date_generated
FROM
invoices as i
LEFT JOIN
csi_tax_recv as c
ON
c.invoice_number = i.id
WHERE
DATE_FORMAT(date_generated,'%Y-%m') < DATE_FORMAT(NOW(),'%Y-%m')
AND
DATE_FORMAT(date_generated,'%Y-%m') >= DATE_FORMAT(NOW() - INTERVAL 12 MONTH,'%Y-%m')
ORDER BY
date_generated
这个查询的唯一问题是它只返回一行吗?不确定为什么。我删除左连接和SUM(c.tax)(这是我认为导致问题)的那一刻,查询效果很好。
最终结果应如下所示:
invoice_amount + total_taxes_for_invoices, tollfree_json, date_generated
干杯。
答案 0 :(得分:1)
正如人们所说,你需要按照你想要得到税额总和的字段进行分组,并用这笔钱进行计算,如下所示:
SELECT
i.tollfree_json,
i.date_generated,
(i.invoice_amount + i.late_fee + SUM(c.tax)) AS amount
FROM
invoices as i JOIN csi_tax_recv as c ON i.id = c.invoice_number
WHERE
DATE_FORMAT(date_generated,'%Y-%m') < DATE_FORMAT(NOW(),'%Y-%m')
AND
DATE_FORMAT(date_generated,'%Y-%m') >= DATE_FORMAT(NOW() - INTERVAL 12 MONTH,'%Y-%m')
GROUP BY
i.tollfree_json,
i.date_generated
ORDER BY
i.date_generated
使用此查询,您将获得每个tollfree_json
和date_generated
组合汇总的税金总和,您可以将invoice_amount和late_fee添加到该总和中,如果这是您查找的内容
答案 1 :(得分:0)
SELECT
invoice_amount + late_fee + SUM(c.tax) AS amount, tollfree_json, date_generated
FROM
invoices as i
LEFT JOIN
csi_tax_recv as c
ON
c.invoice_number = i.id
WHERE
DATE_FORMAT(date_generated,'%Y-%m') < DATE_FORMAT(NOW(),'%Y-%m')
AND
DATE_FORMAT(date_generated,'%Y-%m') >= DATE_FORMAT(NOW() - INTERVAL 12 MONTH,'%Y-%m')
GROUP BY date_generated
ORDER BY
date_generated
查看您的查询,我通常会在聚合之前对所有内容进行分组,但在这种情况下,我不确定它是否有意义。因此,按照您的订单分组(date_generated_)会将它们分组到相关的发票日期。
答案 2 :(得分:0)
正如Vyskol在他的评论中所提到的,我也确定你需要使用group by子句,而不是在聚合函数中使用所有字段。
试试这个,希望这有效:
SELECT
i.tollfree_json,
i.date_generated,
SUM(i.invoice_amount + i.late_fee + c.tax) AS amount
FROM
invoices as i JOIN csi_tax_recv as c ON i.id = c.invoice_number
WHERE
DATE_FORMAT(date_generated,'%Y-%m') < DATE_FORMAT(NOW(),'%Y-%m')
AND
DATE_FORMAT(date_generated,'%Y-%m') >= DATE_FORMAT(NOW() - INTERVAL 12 MONTH,'%Y-%m')
GROUP BY
i.tollfree_json,
i.date_generated
ORDER BY
i.date_generated