如何添加税,然后乘以mysql中的价格

时间:2017-03-20 12:21:57

标签: mysql

我正在尝试添加税,并将结果乘以总价。

以下是表格 "电荷"表 Charge Table

CHARGE_TYPE

Charge_type

TAX_TYPE

Tax Type

收费类型税单

Tax list by Charge type

我想计算税金和乘以每个charge_id的金额 我尝试过这种方式:

SELECT  `charge_id` AS  "Charge ID", SUM( tt.percentage ) AS  "Tax"
FROM charge c, charge_type ct, tax_type tt, charge_type_tax_list cttl
WHERE tt.tax_type_id = cttl.tax_type_id
GROUP BY c.charge_type_id, c.charge_id
LIMIT 0 , 30

2 个答案:

答案 0 :(得分:2)

您正在使用二十多年前冗余的连接语法。无论哪本书或课程或教程教你这种过时的语法,都要退出。这种语法容易出错,正如您自己的查询明确显示的那样。您的查询转换为正确的连接是:

SELECT  `charge_id` AS  "Charge ID", SUM( tt.percentage ) AS  "Tax"
FROM charge c
CROSS JOIN charge_type ct
CROSS JOIN tax_type tt
INNER JOIN charge_type_tax_list cttl ON tt.tax_type_id = cttl.tax_type_id
GROUP BY c.charge_type_id, c.charge_id
LIMIT 0 , 30

您正在将所有费用记录与所有charge_type记录和所有tax_type记录组合在一起。在您的示例中,6 x 3 x 3 = 54条记录。这毫无意义。您可能希望首先只加入相关记录。

您真正想要做的是将费用加入税金:

select
  c.charge_id,
  tax.tax_sum,
  c.amount,
  c.amount * (1 + coalesce(tax.tax_sum, 0)) as taxed_amount
from charge c
left join
(
  select
    cttl.charge_type_id,
    sum(tt.percentage) as tax_sum
  from charge_type_tax_list cttl
  join tax_type tt on tt.tax_type_id = cttl.tax_type_id
  group by cttl.charge_type_id
) tax on tax.charge_type_id = c.charge_type_id;

答案 1 :(得分:1)

您可以在表格之间执行INNER JOIN并计算按费用percentage分组的相应id。下面的查询可以解决这个问题:

SELECT charge.charge_type_id, (SUM(percentage) + 1) * charge.amount AS total_tax
FROM charge INNER JOIN charge_type ON charge.charge_type_id = charge_type.charge_type_id 
INNER JOIN charge_type_tax_list ON charge_type.id = charge_type_tax_list.charge_type_id 
INNER JOIN tax_type ON charge_type_tax_list.tax_type_id = tax_type.tax_type_id GROUP BY charges.id;