Hi,m Hopnig you can help me. New enough to SQL. I have 2 tables. 1 is Customer information with dates we tried to contact them and the other is product information that each customer has purchased.
1st table - CUSTOMER
|Customer Key|Contact Date|
|317984|03/10/2021|
|317984|06/10/2021|
|317984|31/10/2021|
CUSTPRODUCT
|Customer Key|Product ID|Product Purchase Date|Product Cost|
|317984|A14781|01/10/2021|20|
|317984|A14781|01/09/2021|20|
|317984|A14781|04/08/2021|20|
WHat I am trying to get is the latest contact date in the month and the total purchases in the 90 days previous to the latest contact. Desired result would be
Customer Key|MAX(CONTACT DATE)| SUM(PRODUCT COST)
317984|31/10/22021|60
What I am getting
Customer Key|MAX(CONTACT DATE)| SUM(PRODUCT COST)
317984|31/10/22021|180
Code is (DA DATE is just a date table which you can join a date and it will return a fiscal period / month)
SELECT MAX(AL2.CONTACT_DATE), AL2.CUSTOMER_KEY, SUM(AL4.PRODUCT_COST) FROM CUSTOMER AL2, DA_DATE AL3, CUSTPRODUCT AL4 WHERE AL2.CONTACT_DATE=AL3.DA_DATE AND AL2.SUBSCRIBER_KEY=AL4.SUBSCRIBER_KEY) AND AL3.DA_FISCAL_PERIOD='202110' AND AL4.PRODUCT_PURCHASE_DATE<= AL2.CONTACT_DATE AND AL4.PRODUCT_PURCHASE_DATE >= AL2.CONTACT_DATE - 90 AND AL2.CUSTOMER_KEY='317984') GROUP BY 2