从两个表中选择并按两个表中的公共列日期进行分组

时间:2015-06-10 12:47:37

标签: mysql

伙计我找了一个解决方案,但无法解决我的问题 如果有人能提供帮助,我将不胜感激 我有三个表term1term2term3,它们具有相同的列 Admdateamountneededamountpaid, 日期格式为yyyy-mm-dd 我需要从三个表中检索total amountpaid,然后group <{1}}检索year

结果应为

year    total
2012    323000
2013    423000

2 个答案:

答案 0 :(得分:0)

尝试这个

select tyear,sum(total)
from (
      select DATEPART(yyyy,date) as tyear ,sum(amountpaid) as total
      from  term1
      group by DATEPART(yyyy,date)
      union all
      select  DATEPART(yyyy,date) as tyear ,sum(amountpaid) as total
      from  term2
      group by DATEPART(yyyy,date)
      union all
      select  DATEPART(yyyy,date) as tyear ,sum(amountpaid) as total
      from  term1
      group by DATEPART(yyyy,date)
   )a group by tyear

答案 1 :(得分:0)

选择tyear,总和(总计)从(选择EXTRACT(YEAR FROM date)作为tyear,sum(amountpaid)作为来自term1 group的总数由tyear union全部选择EXTRACT(YEAR FROM date)作为tyear,sum(amountpaid)as tyear union的term2 group总数选择摘要(年份从日期)作为tyear,总和(amountpaid)作为总计从term1 group by tyear)a group by tyear