假设我有两个名为tbl1和tbl2的表(不同的列和ID),并且使用以下查询获得每个表的每月总数:
query1:
SELECT MONTHNAME(tbl1_date), SUM(col1+col2+col3+col4)
FROM myTbl1
GROUP BY YEAR(tbl1_date), MONTH(tbl1_date);
query2:
SELECT MONTHNAME(tbl2_date), SUM(col1+col2+col3+col4+col5+col6)
FROM myTbl2
GROUP BY YEAR(tbl2_date), MONTH(tbl2_date);
如何从query1中减去query2并获得SUM的差值?
答案 0 :(得分:1)
加入两个查询,然后减去。
SELECT t1.month, t1.year, t1.total - t2.total AS diff
FROM (
SELECT MONTHNAME(tbl1_date) AS month, YEAR(tbl1_date) AS year, SUM(col1+col2+col3+col4) AS total
FROM myTbl1
GROUP BY YEAR(tbl1_date), MONTH(tbl1_date)
) AS t1
JOIN (
SELECT MONTHNAME(tbl2_date) AS month, YEAR(tb2_date) AS year, SUM(col1+col2+col3+col4+col5+col6) AS total
FROM myTbl2
GROUP BY YEAR(tbl2_date), MONTH(tbl2_date)
) AS t2 ON t1.month = t2.month AND t1.year = t2.year
答案 1 :(得分:0)
如果表可以具有不同的月份和,则您需要所有行,那么您确实需要full join
。 MySQL不支持该功能,但是在这种情况下,您可以使用union all
和group by
:
SELECT yyyy, mon, SUM(s) - SUM(s2) as diff
FROM ((SELECT YEAR(tbl1_date) as yyyy,
MONTHNAME(tbl1_date) as mon,
SUM(col1+col2+col3+col4) as s1, 0 as s2
FROM myTbl1
GROUP BY YEAR(tbl1_date), MONTH(tbl1_date)
) UNION ALL
(SELECT YEAR(tbl2_date) as yyyy,
MONTHNAME(tbl2_date) as mon,
0, SUM(col1+col2+col3+col4) as s2
FROM myTbl12
GROUP BY YEAR(tbl2_date), MONTH(tbl2_date)
)
) ym
GROUP BY yyyy, mon;