简体   繁体   中英

SQL Aggregate on Two tables

Table A has millions of records from 2014, Using Oracle

ID   Sales_Amount  Sales_Date
1      10           20/11/2014
1      10           22/11/2014
1      10           22/12/2014
1      10           22/01/2015     
1      10           22/02/2015         
1      10           22/03/2015     
1      10           22/04/2015     
1      10           22/05/2015 
1      10           22/06/2015     
1      10           22/07/2015
1      10           22/08/2015
1      10           22/09/2015    
1      10           22/10/2015     
1      10           22/11/2015  

Table B

ID   ID_Date
1    22/11/2014
2    01/12/2014

I want sum of totals for 6 months as well as 1 year for ID 1 taking starting
date from Table B as 22/11/2014

Output Sales_Amount_6Months Sales_Amount_6Months
1               70                 130   

Shall I use add_months in this case?

Yes, you can use ADD_MONTHS() and conditional aggregation :

SELECT b.id,
       SUM(CASE WHEN a.sales_date between b.id_date AND ADD_MONTHS(b.id_date,6) THEN a.sales_amount ELSE 0 END) as sales_6_month,
       SUM(CASE WHEN a.sales_date between b.id_date AND ADD_MONTHS(b.id_date,12) THEN a.sales_amount ELSE 0 END) as sales_12_month
FROM TableB b
JOIN TableA a
 ON(b.id = a.id)
GROUP BY b.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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