SQL连接用于按商店和产品比较今年和去年的销售额

时间:2019-02-22 03:20:12

标签: sql left-join

我想按商店和产品比较今年与最近的销售情况。

我的SQL背后的想法是创建一个24个月滚动数据的基表,并在交易日期-1年内执行联接。我的数据是按日期,商店和产品汇总的,这有点复杂。

我的代码如下。我的问题是,当我进行左联接时,今年和去年的数字不匹配。例如,去年2月19日的销售额应等于今年2月18日的销售额,但我没有得到这个结果。

我的猜测是,去年有一些商店和产品在今年不可用,但我不知道如何解决。我尝试了完全加入,但人数也没有。请感谢任何反馈!

-- 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;

1 个答案:

答案 0 :(得分:0)

您已加入-trunc(dateadd(year, -1, ty.business_date)) = ly.business_date;

您正在尝试比较今年特定日期和去年(22/02/2019 with 22/02/2018)

的销售额

在您的表中,这两天是否都有数据,表中的汇总样本数据可能有助于编写查询。

查询-

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)
);