可以使用 stack 将少量数据直接写在sql中,然后用于验证是否正确
1、每个省累计销量前1名的城市 t1(pro_name,city_name,sale_num,sale_date)
源数据:
'河北','石家庄','1','2022-01-01'
,'河北','石家庄','2','2022-01-02'
,'河北','石家庄','3','2022-01-03'
,'河北','张家口','2','2022-01-02'
,'河北','张家口','3','2022-01-03'
,'河北','张家口','2','2022-01-02'
,'陕西','西安','0','2022-01-02'
,'陕西','西安','1','2022-01-03'
,'陕西','西安','2','2022-01-02'
,'陕西','延安','0','2022-01-02'
,'陕西','延安','1','2022-01-03'
,'陕西','延安','0','2022-01-02'
结果:
city_name sum_sale
张家口 7
西安 3
答:
sql
with temp_data as (
select stack(12,
'河北','石家庄','1','2022-01-01'
,'河北','石家庄','2','2022-01-02'
,'河北','石家庄','3','2022-01-03'
,'河北','张家口','2','2022-01-02'
,'河北','张家口','3','2022-01-03'
,'河北','张家口','2','2022-01-02'
,'陕西','西安','0','2022-01-02'
,'陕西','西安','1','2022-01-03'
,'陕西','西安','2','2022-01-02'
,'陕西','延安','0','2022-01-02'
,'陕西','延安','1','2022-01-03'
,'陕西','延安','0','2022-01-02'
) as (pro_name,city_name,sale_num,sale_date)
)
select
*
from (
select
t.pro_name,
t.city_name,
t.sale_cnt,
row_number() over(partition by pro_name order by sale_cnt desc) as rnk
from (
select
pro_name,
city_name,
sale_num,
sum(sale_num) as sale_cnt
from temp_data
group by pro_name,city_name
) t
) t1
where t1.rnk = 1
;
lag: 将数据按照从小到大的顺序,将首次出现的,数据字段往后置一行,并且第一条数据使用Null填充
lead:将数据按照从小到大的顺序,将首次出现的数据往后置一行,并且第一条数据使用Null进行填充
2、求股票的波峰和波谷
波峰:当天的股票价格大于前一天和后一天
波谷:当天的股票价格小于前一天和后一天
数据准备: stock表有3个字段: stock_name(股票名称)、stock_price(股票价格)、stats_date(日期)
源数据:
'A','20210621','13'
'A','20210622','11'
'A','20210623','17'
'A','20210624','12'
'A','20210625','14'
'B','20210621','16'
'B','20210622','12'
'B','20210623','12'
'B','20210624','17'
'B','20210625','13'
结果:
stock_name stats_date stock_price price_type
A 20210621 13 其他
A 20210622 11 波谷
A 20210623 17 波峰
A 20210624 12 波谷
A 20210625 14 其他
B 20210621 16 其他
B 20210622 12 其他
B 20210623 12 其他
B 20210624 17 波峰
B 20210625 13 其他
答:
with temp_data as (
select stack(10,
'A','20210621','13'
,'A','20210622','11'
,'A','20210623','17'
,'A','20210624','12'
,'A','20210625','14'
,'B','20210621','16'
,'B','20210622','12'
,'B','20210623','12'
,'B','20210624','17'
,'B','20210625','13'
) as (stock_name,stock_date,stock_price)
)
select
t.stock_name,
t.stock_date,
t.stock_price,
case when t.stock_price < t.lag_price and t.stock_price < t.lead_price then '波谷'
when t.stock_price > t.lag_price and t.stock_price > t.lead_price then '波峰'
else '其他' end as price_type
from (
select
stock_name,
stock_date,
stock_price,
lag(stock_price,1) over(partition by stock_name order by stock_date ) as lag_price,
lead(stock_price,1) over(partition by stock_name order by stock_date ) as lead_price
from temp_data
) t