从两个表中按月求和

fruv7luv  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(250)

如何从两个表中按月求和?
我有两张table:

1)costs_1

-id
-total
-updated_at(timestamp)

2)costs_2

-id
-total_1
-updated_at_1(timestamp)

结果表需要有下一列:

-total
-total_1
-month

例如,如果我有一个表,我将执行下一个查询:

SELECT SUM(total), MONTH(updated_at), YEAR(updated_at) FROM product_sale GROUP BY MONTH(updated_at), YEAR(updated_at) ORDER by MONTH(updated_at)
2jcobegt

2jcobegt1#

试试这个:

SELECT total, total_1, MONTHNAME(costs_1.updated_at) from costs_1 INNER JOIN costs_2 
ON 
MONTH(costs_1.updated_at)=MONTH(costs_2.updated_at)
yzckvree

yzckvree2#

我相信你想要这样的东西。

SELECT t1.y year,
       t1.m month,
       t1.total,
       t2.total
FROM
(
    SELECT YEAR(updated_at) y, 
           MONTH(updated_at) m, 
           SUM(total) total
    FROM costs_1
    GROUP BY YEAR(updated_at), MONTH(updated_at) 
) t1
JOIN
(
    SELECT YEAR(updated_at_1) y, 
           MONTH(updated_at_1) m, 
           SUM(total_1) total
    FROM costs_2
    GROUP BY YEAR(updated_at_1), MONTH(updated_at_1) 
) t2 ON t1.y = t2.y and t1.m = t2.m

但是,在这个解决方案中,如果 costs_1 或者 costs_2 没有任何月份记录。如果您想要完全连接,您必须在mysql中使用两个外部连接来模拟它,如下所示:

SELECT t1.y year,
       t1.m month,
       COALESCE(t1.total, 0),
       COALESCE(t2.total, 0)
FROM
(
    SELECT YEAR(updated_at) y, 
           MONTH(updated_at) m, 
           SUM(total) total
    FROM costs_1
    GROUP BY YEAR(updated_at), MONTH(updated_at) 
) t1
LEFT JOIN
(
    SELECT YEAR(updated_at_1) y, 
           MONTH(updated_at_1) m, 
           SUM(total_1) total
    FROM costs_2
    GROUP BY YEAR(updated_at_1), MONTH(updated_at_1) 
) t2 ON t1.y = t2.y and t1.m = t2.m

   UNION

SELECT t2.y year,
       t2.m month,
       COALESCE(t1.total, 0),
       COALESCE(t2.total, 0)
FROM
(
    SELECT YEAR(updated_at) y, 
           MONTH(updated_at) m, 
           SUM(total) total
    FROM costs_1
    GROUP BY YEAR(updated_at), MONTH(updated_at) 
) t1
RIGHT JOIN
(
    SELECT YEAR(updated_at_1) y, 
           MONTH(updated_at_1) m, 
           SUM(total_1) total
    FROM costs_2
    GROUP BY YEAR(updated_at_1), MONTH(updated_at_1) 
) t2 ON t1.y = t2.y and t1.m = t2.m

相关问题