简体   繁体   English

从两个表中获取字段的总和和差异

[英]get sum and difference of fields from two tables

I have two tables我有两张桌子

  1. sales:销售量:
sale_date发售日期 total_amount总金额
2021-03-24 2021-03-24 59000 59000
2021-03-24 2021-03-24 25000 25000
2021-03-25 2021-03-25 88000 88000
2021-03-25 2021-03-25 10000 10000
2021-03-26 2021-03-26 67000 67000
2021-03-27 2021-03-27 99000 99000
  1. credit_sales:信用销售:
credit_sale_date credit_sale_date amount数量
2021-03-24 2021-03-24 10000 10000
2021-03-24 2021-03-24 2000 2000
2021-03-24 2021-03-24 3000 3000
2021-03-25 2021-03-25 1000 1000
2021-03-25 2021-03-25 5000 5000
2021-03-25 2021-03-25 6000 6000
2021-03-26 2021-03-26 22000 22000
2021-03-27 2021-03-27 15000 15000

Expected Result:预期结果:

date日期 total_amount总金额 cash_amount现金金额 credit_amount信用金额
2021-03-24 2021-03-24
2021-03-25 2021-03-25
2021-03-26 2021-03-26
2021-03-27 2021-03-27

total_amount is the sum of 'total_amount' from sales table of a particular date total_amount 是特定日期销售表中“total_amount”的总和

credit_amount = sum of 'amount' from credit_sales table of the particular date credit_amount = 特定日期 credit_sales 表中“金额”的总和

cash_amount = sum of 'total_amount' from sales table - sum of 'amount' from credit_sales table of the particular date cash_amount = sales 表中的“total_amount”之和 - 特定日期的 credit_sales 表中的“amount”之和

select
    sale_date as date, sum(DISTINCT total_amount) as total_amount, sum(DISTINCT amount) as credit_amount, sum(DISTINCT total_amount) + sum(DISTINCT amount) as cash_amount
from
    sales, credit_sales
where 
    sales.sale_date = credit_sales.credit_sale_date
GROUP BY sales.sale_date

Union and group工会和团体

select sale_date, sum(total_amount) as total_amount,
   sum(credit_amount) as credit_amount,
   sum(total_amount) - sum(credit_amount) as cash_amount
from (
    select sale_date, total_amount, 0 as credit_amount
    from sales 
    union all
    select credit_sale_date, 0 as total_amount, amount as credit_amount
    from credit_sales
) t
group by sale_date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM