从两个表中获取每年的总和

时间:2019-08-10 15:35:41

标签: mysql sql database

我的数据库中有两个表salespurchases,我希望在一次咨询中获得这两个表每年的总金额。表的结构大致如下所示:

|    sales   | |  purchases | 
|------------| |------------|
| sales_id   | | purch_id   |
| date       | | date       |
| amount     | | amount     |
| account    | | account    |

目前,我仅具有以下用于销售的代码,但我需要在单个查询中获得两个表的每年总计

SELECT YEAR(date) as year, SUM(amount) AS year_total 
FROM sales
GROUP BY YEAR(date)

2 个答案:

答案 0 :(得分:1)

您可以加入相关的子查询

select t1.year, ifnuLL(t1.year_total_sales,0), ifnull(t2.year_total_purchases,0)
from (
  SELECT YEAR(date) as year, SUM(amount) AS year_total_sales
  FROM sales
  GROUP BY YEAR(date)
) t1
INNER JOIN (
  SELECT YEAR(date) as year, SUM(amount) year_total_purchases
  FROM purchases
  GROUP BY YEAR(date)
)  t2 on t1.year = t2.year

如果其中一个表中缺少年份,则可以在年份上使用

    select t3.year, t1.year_total_sales, t2.year_total_purchases
    from (
    select year(date) year 
    from sales
    union 
    select year(date)
    from purchases
    ) t3 
    left join (
      SELECT YEAR(date) as year, SUM(amount) AS year_total_sales
      FROM sales
      GROUP BY YEAR(date)
    ) t1 ON t3.year = t1.year
    LEFT  JOIN (
      SELECT YEAR(date) as year, SUM(amount) year_total_purchases
      FROM purchases
      GROUP BY YEAR(date)
    )  t2 on t3.year = t2.year  

答案 1 :(得分:1)

MySQL不支持full join。因此,我建议使用union all / group by

select year(date), sum(sale_amount) as sales, sum(purchase_amount) as purchases
from ((select date, amount as sale_amount, 0 as purchase_amount
       from sales
      ) union all
      (select date, 0, amount
       from purchases
      )
     ) sp
group by year(date);

这将返回数据中所有年份的行,即使没有买卖也是如此。