如何计算百分比并生成以下结果



我有一个表架构

创建表"费用"( 'charge_id' int(11) 不空AUTO_INCREMENT, "selling_date"日期默认为空, "金额"十进制(10,2)默认空值, 'is_deleted' tinyint(1) 不为空 默认值 '0', 'charge_type_id' int(11) 默认空, 主键("charge_id") );
创建表"charge_type"( 'charge_type_id' int(11) 不空AUTO_INCREMENT, 'charge_type' 瓦尔查尔(20) 不为空, 'is_deleted' tinyint(1) 默认 '0', 主键("charge_type_id") );
创建表"charge_type_tax_list"( 'tax_type_id' int(11) 不为空, 'charge_type_id' int(11) 不为空, 主键("tax_type_id"、"charge_type_id") );
创建表"tax_type"( 'tax_type_id' int(11) 不为空AUTO_INCREMENT, 'tax_type' 瓦尔查尔(35) 不为空, "百分比"十进制(5,4)不为空默认值"0.0000", 'is_deleted' tinyint(1) 默认 '0', 主键("tax_type_id") );
插入充电 ( "selling_date", "金额", "is_deleted", "charge_type_id" ) 值 ("2013-12-01", 50, 0, 1), ("2013-12-01", 20, 0, 2), ("2013-12-02", 40, 0, 1), ("2013-12-02", 30, 0, 3), ("2013-12-02", 30, 1, 1), ("2013-12-03", 10, 0, 1);
插入charge_type ( "charge_type_id", "charge_type", "is_deleted" ) 值 (1、"房费", 0), (2、"零食费",0), (3、"删除费用",1);
插入charge_type_tax_list ( "tax_type_id", "charge_type_id" ) 值 (1, 1), (2, 1), (3, 1), (1, 2), (1,3);
插入tax_type ( "tax_type_id", "tax_type" , "百分比", "is_deleted" ) 值 (1, "消费税", 0.05, 0), (2, "HRT", 0.04, 0), (3、"删除税",0.10,1);

我希望您生成一个查询,列出所有费用和税款计算的总计 使用给定的架构,查询应生成:

销售日期 费用类型 金额 税金 2013-12-01 房费 50.00 4.50 2013-12-01 小吃收费 20.00 1.00 2013-12-02 房间费 40.00 3.60 2013-12-03 房费 10.00 0.90

不显示已删除的费用(is_deleted被标记) 不显示具有已删除(is_deleted已标记)charge_types的费用 不要考虑已删除tax_type(is_deleted),但仍应显示包含charge_type)

请帮助我,我急需它。谢谢

请阅读 MySQL 加入 易于理解如何使用连接。下面是一个查询,它应该通过联接公共属性上的表来给出所需的结果。

SELECT A.`selling_date` AS `Selling Date`, B.`charge_type` AS `Charge Type`
, A.`amount` AS `Amount`, (A.`amount` *  D.`percentage`) AS `Tax` FROM 
`charge` A LEFT JOIN  
`charge_type` B ON A.`charge_type_id`=B.`charge_type_id` INNER JOIN 
`charge_type_tax_list` C ON B.`charge_type_id`=C.`charge_type_id` 
INNER JOIN `tax_type` D ON C.`tax_type_id`=D.`tax_type_id`
WHERE 
A.`is_deleted`=0 AND B.`is_deleted`=0 AND
D.`is_deleted`=0;

这是一个SQL小提琴演示

下面的查询将获得您想要的结果

select charge.selling_date as SellingDate, 
charge.amount as Amount,
charge_type.charge_type as ChargeType,
sum(charge.amount * tax_type.percentage) as Tax
From charge
inner join charge_type on charge.charge_type_id=charge_type.charge_type_id,
tax_type
where charge.is_deleted=0 and charge_type.is_deleted=0 and tax_type.is_deleted=0
group by charge.selling_date, charge.amount,charge_type.charge_type

最新更新