SQL Server want total revenue for last 30 days from max date and age of customers between 25 and 30 calculated from DOB

hrirmatl  于 2023-05-05  发布在  其他
关注(0)|答案(2)|浏览(230)

For all customers aged between 25 to 35 years find what is the net total revenue generated by these consumers in last 30 days of transactions from max transaction date available in the data?

Tried many things but not able to solve this

My code

SELECT
SUM(total_amt) [NET TOTAL REVENUE]
FROM Transactions 
                  INNER JOIN Customer ON Transactions.cust_id = Customer.customer_Id
WHERE tran_date >= DATEADD(day,-30,MAX(tran_date)) and DATEDIFF(YEAR,DOB,tran_date) between 25 and 30
h7wcgrx3

h7wcgrx31#

I would recommend window functions to get the maximum date:

SELECT SUM(t.total_amt) as net_total_revenue
FROM (SELECT t.*,
             MAX(t.tran_date) OVER () as max_tran_date
      FROM Transactions t
     ) t JOIN
     Customer c
     ON t.cust_id = c.customer_Id
WHERE t.tran_date >= DATEADD(day, -30, t.max_tran_date) AND 
      t.tran_date >= DATEADD(YEAR, 25, c.DOB) AND
      t.tran_date < DATEADD(YEAR, 31, c.DOB);

Some notes:

  • Qualify all column names so it is clear where they come from.
  • DATEDIFF() does not do what you think it does. It counts the number of Jan 1sts between two dates. DATEADD() is more accurate.
  • Don't name column aliases with spaces. Use names that don't need to be escaped.
cpjpxq1n

cpjpxq1n2#

Tried to do it through temp tables

select  t.cust_id,        
sum(convert(float,t.total_amt)) as net_sales  
into #temp4  
from  Transactions t  
where t.cust_id in (select c.customer_id from Customer c where DATEDIFF(YY,DOB,getdate()) between 25 and 36)  
group by t.cust_id,t.tran_date  
having t.tran_date > DATEADD(DAY, -30, max(t.tran_date))   
order by t.tran_date desc  
GO  
select t1.cust_id, sum(net_sales) as net_sales from #temp4 t1     
group by t1.cust_id    
order by sum(net_sales) desc      
drop table #temp4

相关问题