繁体   English   中英

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

[英]select from two tables and group by a common column date in both tables

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

结果应该是

year    total
2012    323000
2013    423000

试试这个

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

select tyear,sum(total) from ( select EXTRACT(YEAR FROM date) as tyear ,sum(amountpaid) as total from term1 group by tyear union all select EXTRACT(YEAR FROM date) as tyear ,sum(amountpaid) as total from term2 group by tyear union all select EXTRACT(YEAR FROM date) as tyear ,sum(amountpaid) as total from term1 group by tyear )a group by tyear

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM