mysql从不同的表中选择乘以列的值和按日期分组

时间:2016-11-23 13:32:00

标签: mysql sql

mysql选择不同表格中的多个列和日期和日期分组

table

2 个答案:

答案 0 :(得分:2)

我建议union all然后汇总:

select date, user, sum(vale)
from ((select t1.user, t1.date, t1.vale from t1) union all
      (select t2.user, t2.date, t2.vale from t2)
     ) t
group by date, user;

如果只想要一个用户(外部查询或每个子查询)的结果,可以添加where user = 'x'

答案 1 :(得分:0)

在派生表中提取年份和月份,并执行union all。然后GROUP BY结果:

select y, m, user, sum(vale)
from
(
    select user, year(date) as y, month(date) as m, vale from t1
    union all
    select user, year(date) as y, month(date) as m, vale from t2
) dt
group by y, m, user