MySQL聚合选择查询返回不正确的数据
Posted
技术标签:
【中文标题】MySQL聚合选择查询返回不正确的数据【英文标题】:MySQL aggregate select query returning incorrect data 【发布时间】:2020-05-31 06:38:04 【问题描述】:我有以下代码:
SELECT gl.account_description AS invoice_total, COUNT(ili.invoice_id) AS total_invoice,
SUM(ili.line_item_amount) AS total_convert
FROM general_ledger_accounts gl JOIN
invoice_line_items ili
ON gl.account_number = ili.account_number JOIN
invoices i
ON ili.invoice_id = i.invoice_id
GROUP BY gl.account_description, i.invoice_date, ili.account_number
HAVING i.invoice_date BETWEEN '2014-04-01' AND '2014-06-30' AND
COUNT(ili.account_number) > 1
ORDER BY account_description DESC;
在我的查询中,我应该返回 10 行数据,而我只有 7 行返回,而且没有一个包含正确的信息。我应该返回的是 general_ledger_accounts 表中的 account_description 列,invoice_line_items 表中的项目计数,invoice_line_items 表中具有相同帐号的 line_item_amount 列的总和。它应该只在日期“2014-04-01”和“2014-06-30”之间的发票中搜索。我应该加入发票表。
谁能看出我在语法上做错了什么来得到错误的结果?
【问题讨论】:
【参考方案1】:显然,您需要 WHERE
子句而不是 HAVING
子句来过滤日期 - 并从 GROUP BY
中删除日期(您没有选择它):
SELECT gl.account_description AS invoice_total,
COUNT(*) AS total_invoice,
SUM(ili.line_item_amount) AS total_convert
FROM general_ledger_accounts gl JOIN
invoice_line_items ili
ON gl.account_number = ili.account_number JOIN
invoices i
ON ili.invoice_id = i.invoice_id
WHERE i.invoice_date BETWEEN '2014-04-01' AND '2014-06-30'
GROUP BY gl.account_description, ili.account_number
HAVING COUNT(*) > 1
ORDER BY account_description DESC;
不知道还有没有其他问题。
【讨论】:
【参考方案2】:我怀疑您想从group by
子句中删除列i.invoice_date
和ili.account_number
。否则,这三列的每个不同值都会得到一条记录,这似乎不是您想要的。
因此,您应该将日期上的过滤器移至where
子句:
SELECT
gl.account_description AS invoice_total,
COUNT(ili.invoice_id) AS total_invoice,
SUM(ili.line_item_amount) AS total_convert
FROM general_ledger_accounts gl
INNER JOIN invoice_line_items ili
ON gl.account_number = ili.account_number
INNER JOIN invoices i
ON ili.invoice_id = i.invoice_id
WHERE
i.invoice_date >= '2014-04-01'
AND i.invoice_date < '2014-07-01'
GROUP BY gl.account_description
HAVING COUNT(ili.account_number) > 1
ORDER BY g1.account_description DESC;
请注意,我将日期的条件修改为使用半开间隔:这样,您不必担心上个月是 30 天还是 31 天(或 28 或 29...);如果有的话,这也可以顺利处理日期的时间部分。
【讨论】:
以上是关于MySQL聚合选择查询返回不正确的数据的主要内容,如果未能解决你的问题,请参考以下文章