SQL 周数据对比(本周VS上周)

SQL本周每天对比上周每天数据

    • 用途:计算周环比(同期)和周对比趋势

#本周和上周每天产量

用途:计算周环比(同期)和周对比趋势

1、获取订单表

// An highlighted block
with ord as (select orderdata,orderid,num from 库名.表名
where orderdate <=date_sub('${zdt.format("yyyy-MM-dd")}',1));
//获取t-1天所有的数据(预定时间其实可以不用限制)

2、获取本周每天的产量
对每一个日期计算出一个周几,并聚合每天的产量
使用到的函数:
pmod:求余数的方法,使用到计算今天是周几
eg:pmod(datediff(’#日期#’,‘2020-03-23’) ,7)+1) 返回周几(1-7),若是没有+1,则返回(0-6)注: 日期为某一个周一

// An highlighted block
,a as (select 
 concat('周', pmod(datediff(orderdata, '2011-01-03'), 7)+1)as `周几` //周几
 ,orderdata
,coalesce(sum(num),0) as `本周产量` //聚合每天的产量
from ord
where orderdata>= date_sub('${zdt.format("yyyy-MM-dd")}',7)
group by concat('周', pmod(datediff(orderdata, '2011-01-03'), 7)+1) ,orderdata);
//取的是2011-01-03这个周一

3、获取上周每天的产量:办法同上

// An highlighted block
,a1 as (
select 
concat('周', pmod(datediff(orderdata, '2011-01-03'), 7)+1)as `周几`
 ,stayin
,coalesce(sum(num),0) as `上周产量`
from ord
where orderdata between date_sub('${zdt.format("yyyy-MM-dd")}',14) and date_sub('${zdt.format("yyyy-MM-dd")}',8)
group by concat('周', pmod(datediff(orderdata, '2011-01-03'), 7)+1),orderdata);

#本周&上周拼接在一起

// An highlighted block
select 
 a.`周几`
,a.orderdata as orderdata01
,a1.orderdata as orderdata02
,concat(a.orderdata ,a.`周几`) as `日期`
,`本周产量`
,`上周产量`
from  a
left join a1
on a.`周几` =a1.`周几` and datediff(a.orderdata, a1.orderdata) = 7
order by a.orderdata;

#结果实例:
SQL 周数据对比(本周VS上周)_第1张图片
SQL 周数据对比(本周VS上周)_第2张图片
代码汇总

// An highlighted block
with ord as (select orderdata,orderid,num from 库名.表名
where orderdate <=date_sub('${zdt.format("yyyy-MM-dd")}',1))

,a as (select 
 concat('周', pmod(datediff(orderdata, '2011-01-03'), 7)+1)as `周几` //周几
 ,orderdata
,coalesce(sum(num),0) as `本周产量` //聚合每天的产量
from ord
where orderdata>= date_sub('${zdt.format("yyyy-MM-dd")}',7)
group by concat('周', pmod(datediff(orderdata, '2011-01-03'), 7)+1) ,orderdata)

,a1 as (
select 
concat('周', pmod(datediff(orderdata, '2011-01-03'), 7)+1)as `周几`
 ,stayin
,coalesce(sum(num),0) as `上周产量`
from ord
where orderdata between date_sub('${zdt.format("yyyy-MM-dd")}',14) and date_sub('${zdt.format("yyyy-MM-dd")}',8)
group by concat('周', pmod(datediff(orderdata, '2011-01-03'), 7)+1),orderdata)

select 
 a.`周几`
,a.orderdata as orderdata01
,a1.orderdata as orderdata02
,concat(a.orderdata ,a.`周几`) as `日期`
,`本周产量`
,`上周产量`
from  a
left join a1
on a.`周几` =a1.`周几` and datediff(a.orderdata, a1.orderdata) = 7
order by a.orderdata;
;

你可能感兴趣的:(SQL应用,sql,大数据,hive)