我正在从簿记系统中提取报告.该系统有一个讨厌的习惯,就是在其内部处理的数据库中放置重复项(而不是首先将其清理干净!)

例如,这是发票125的总计表:

+------------+-----------+----------+
| invoice_id | code      | amount   |
+------------+-----------+----------+
|        125 | sub_total | 300.0000 |
|        125 | tax       |  30.0000 |
|        125 | total     | 330.0000 |
|        125 | sub_total | 300.0000 |
|        125 | tax       |  30.0000 |
|        125 | total     | 330.0000 |
+------------+-----------+----------+

以及相同id的发票表

+-----+----------+
| id  | amount   |
+-----+----------+
| 125 | 330.0000 |
+-----+----------+

我希望生成一段时间内的总销售额和税费(针对澳大利亚BAS)

我的MWE查询(如果数据是干净的,它就会工作)是

select sum(a.amount) as total_sales, sum(c.amount) as total_GST
from 7cn_invoices a 
    INNER JOIN 7cn_invoice_totals c ON a.id = c.invoice_id
where c.code = 'tax';

然而,由于total表中有重复项,我得到的总销售额是它们本应的两倍.解决这个问题的最佳方法是什么(除了修补代码)?

推荐答案

您可以通过使用带有DISTINCT的子查询来删除重复项

CREATE TABLE 7cn_invoice_totals  (
  `invoice_id` INTEGER,
  `code` VARCHAR(9),
  `amount` DECIMAL(10,4)
);

INSERT INTO 7cn_invoice_totals 
  (`invoice_id`, `code`, `amount`)
VALUES
  ('125', 'sub_total', '300.0000'),
  ('125', 'tax', '30.0000'),
  ('125', 'total', '330.0000'),
  ('125', 'sub_total', '300.0000'),
  ('125', 'tax', '30.0000'),
  ('125', 'total', '330.0000');
CREATE TABLE 7cn_invoices  (
  `id` INTEGER,
  `amount` INTEGER
);

INSERT INTO 7cn_invoices 
  (`id`, `amount`)
VALUES
  ('125', '330.0000');
select sum(a.amount) as total_sales, sum(c.amount) as total_GST
from  7cn_invoices a 
    INNER JOIN (SELECT DISTINCT `invoice_id`, `code`, `amount`  FROM 7cn_invoice_totals) c ON a.id = c.invoice_id
where c.code = 'tax';
total_sales | total_GST
----------: | --------:
        330 |   30.0000

db<>fiddle 100

Mysql相关问答推荐

MySQL问题难以将文本字符串转换为正确的日期格式

Google Sheet查询以提取数据并用值替换复选框.(差异)

找出同一表中列A中的每个值在列B中出现的次数

在MySQL CLI中,是否有自动完成过程的方法?

奇怪的MySQL SELECT循环;但不是\G

使用Check查看过go 两个月是否完成了IRM Meetup

WordPress的sql命令从帖子中删除随机文本

SQL Select 最大值和平均值

是否可以使用以EXPLAIN EXTENDED ...开头的 SQL 语句修改数据?

高效的 SQL 查询,用于计算半小时时间序列中已发生的行的一部分

为什么这个查询需要超过 5 秒才能运行?

创建表时我的 SQL 语句有什么问题

SQL从字典中的键获取值

Ansible 幂等 MySQL 安装 Playbook

mysqli_fetch_array() 期望参数 1 为 mysqli_result,布尔值

从 MySQL 中的日、月、年字段创建日期

加快 mysql 转储和导入

Sequelize:销毁/删除表中的所有记录

MySQL - 错误 1045 - 访问被拒绝

获取最后一组不同的记录