表A有2014年的数百万条记录,使用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
表B
ID ID_Date
1 22/11/2014
2 01/12/2014
我希望6个月的总和以及ID 1开始时的1年总和 表B中的日期为 22/11/2014
Output Sales_Amount_6Months Sales_Amount_6Months
1 70 130
在这种情况下,我应该使用add_months
吗?
答案 0 :(得分:7)
是的,您可以使用ADD_MONTHS()
和条件聚合:
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