简体   繁体   English

显示来自不同不相关表的两个总和

[英]Displaying two sums from different unrelated tables

I have 2 tables.我有 2 张桌子。 One contains expenses, the other contains earnings.一个包含费用,另一个包含收入。 my_costs:我的成本: 在此处输入图像描述

my_earnings:我的收入:

在此处输入图像描述

From these two tables, I want to get data:从这两个表中,我想获取数据:

  1. Grouping a period by month and year按月和年对时间段进行分组
  2. The amount of expenses in the period本期费用金额
  3. Average expenses per day in the period期间每日平均费用
  4. Amount of earnings in the period本期收入金额

I am using the following query:我正在使用以下查询:

SELECT DATE_FORMAT(my_costs.DATE, "%M-%Y") AS Period, SUM(my_costs.sum) AS Costs,
ROUND(SUM(my_costs.sum)/DAY(LAST_DAY(my_costs.date)), 0) AS Average,

SUM(my_earnings.sum)

FROM my_costs

LEFT JOIN my_earnings ON DATE_FORMAT(my_costs.DATE, "%M-%Y") = DATE_FORMAT(my_earnings.date, "%M-%Y")

GROUP BY DATE_FORMAT(my_costs.DATE, "%M-%Y")
ORDER BY Period DESC

This request successfully gives me the period, costs and earnings.这个请求成功地给了我周期、成本和收益。 But the amount of earnings shown is incorrect.但显示的收入金额不正确。 The numbers are much higher than expected, should be no more than 10,000 per month数量远高于预期,每月应不超过10,000

在此处输入图像描述

Aggregating after joins can be inaccurate, because rows are duplicated or lost.连接后聚合可能不准确,因为行重复或丢失。 I would recommend using union all and then aggregating:我建议使用union all然后聚合:

SELECT DATE_FORMAT(ce.DATE, '%M-%M') AS Period,
       SUM(ce.costs) AS Costs, SUM(ce.Expenses) as expenses,
        ROUND(SUM(ce.sum)/DAY(LAST_DAY(ce.date)), 0) AS daily_Average
FROM ((SELECT date, sum as costs, 0 as expenses
       FROM my_costs
      ) UNION ALL
      (SELECT date, 0, sum
       FROM my_earnings
      )
     ) ce
GROUP BY period
ORDER BY MIN(ce.DATE) DESC;

Note that I changed the ORDER BY so the results are in time order.请注意,我更改了ORDER BY ,因此结果按时间顺序排列。

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

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