简体   繁体   中英

SQL join for comparing this year vs last year sales by store and by product

I'm trying to compare this year vs last sales by store and by product.

The idea behind my SQL is to create a base table for 24 months rolling data and perform a join on transaction date - 1 year. This is somewhat complicated that my data is aggregated by date, by store and by product.

My code is as below. And my issue is that when i do a left join, the numbers for this year and last year doesn't match up. For example, feb-19 last year sales should equal to feb-18 this year sales, but I am not getting this result.

My guess is that last year has certain stores and products that are not available this year but I have no idea how to resolve this. I tried a full join, but the numbers are also off. Appreciate any feedback please!

-- extract sales by day, store, product
select business_date, store_code, product_code, 
sum(sales) as sales
into #temp1
from sales_table
where business_date >= date_trunc('month', dateadd('month', -24, sysdate))
group by business_date, store_code, product_code;


-- compare this year against last year
select ty.*, ly.sales as sales_ly
into #temp2
from #temp1 ty left join #temp1 ly
on ty.product_code = ly.product_code
and ty.store_code = ly.store_code 
and trunc(dateadd(year, -1, ty.business_date)) = ly.business_date;

-- check
select to_char(business_date, 'yyyymm'), sum(sales) ty, sum(sale_ly) as ly
from #temp2
group by to_char(business_date,'yyyymm')
order by 1;

You have join - trunc(dateadd(year, -1, ty.business_date)) = ly.business_date;

You are trying to compare sales of particular day of this year with last year (22/02/2019 with 22/02/2018)

In your table, do you have data for both of these days, aggregated sample data from your table could help in writing the query.

Query -

with  sales_tab as (
select '2019/02/22' as date1, 123 as store, 456 as prod, 20 sales from dual
union
select '2019/02/23' as date1, 123 as store, 456 as prod, 30 as sales from dual
union
select '2019/02/24' as date1, 123 as store, 456 as prod, 40 sales from dual
union
select '2018/02/22' as date1, 123 as store, 456 as prod, 60 sales from dual
union
select '2018/02/23' as date1, 123 as store, 456 as prod, 70 as sales from dual
union
select '2018/02/25' as date1, 123 as store, 456 as prod, 80 sales from dual)
select 
t1.date1, t2.date1, t1.store, t1.prod, t1.sales this_year, t2.sales prev_year
from sales_tab t1 left outer join sales_tab t2 on 
(t1.store=t2.store 
and t1.prod=t2.prod
and cast(substr(t1.date1,1,4) as int)-1=cast(substr(t2.date1, 1,4) as int)
and substr(t1.date1,6,2)=substr(t2.date1,6,2)
and substr(t1.date1,9,2)=substr(t2.date1,9,2)
);

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