[英]mysql query to get results from 2 tables by adding sum according to date
我有这样的查询,我能够分别获取两个表的数据。 这个概念是我要按月分组金额。 从任何一张表中,我都可以正确检索金额,但是我必须从两个表格中获得金额之和,具体取决于月份。
(select SUM(amount) as amount
, month(reciept_date) as month
, year(reciept_date) as year
from sg_chool
where academic_year = '2'
group by MONTH(reciept_date))
UNION ALL
(select SUM(amount_paid) as amount
, month(reciept_date) as month
, year(reciept_date) as year
from sg_fees
where academic_year = '2'
group by MONTH(reciept_date))
尝试这个
SELECT sum(temp.amount) as amount, temp.month, temp.year
FROM (
(select SUM(amount) as amount
, month(reciept_date) as month
, year(reciept_date) as year
from sg_chool
where academic_year = '2'
group by MONTH(reciept_date))
UNION ALL
(select SUM(amount_paid) as amount
, month(reciept_date) as month
, year(reciept_date) as year
from sg_fees
where academic_year = '2'
group by MONTH(reciept_date))
) as temp
GROUP BY temp.month;
这可能满足您的需求:
SELECT
(school.amount + fees.amount) AS amount
, school.month
, school.year
FROM
(SELECT SUM(amount) AS amount
, month(reciept_date) AS month
, year(reciept_date) AS year
FROM sg_chool
WHERE academic_year = '2'
GROUP BY MONTH(reciept_date)) AS school
JOIN
(SELECT SUM(amount_paid) AS amount
, month(reciept_date) AS month
FROM sg_fees
WHERE academic_year = '2'
GROUP BY MONTH(reciept_date)) AS fees
USING (month)
您可以在这里尝试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.