求最大的连续数

摘要:求最大的连续数


原理:同属性的序列差等值,由等差序列派生。

详细描述:

1、首先看下表结构

字段说明:serial_no 根据月份派生的连续号;city:城市;YM:YYYYMM格式的月份;price:当月价格;previous_price:上月价格;link_ratio:价格环比{(当月价格-上月价格)/上月价格}

2、计算过程

为计算方便,我们可以根据价格环比值派生出字段(ratio_sign,int,价格环比是增长还是下降)的值。update [TB_CITY_PRICE] set ratio_sign=sign(link_ratio),这样,ratio_sign属性值中,1为增长,-1为下降;

然后根据连续号serial_no 和ratio_sign,计算哪些月份是连续的。

alter table TB_CITY_PRICE add serial_up_value int; --连续增长值
update a  set a.serial_up_value=a.link_sign
from
(
select *,serial_no-(select count(*) from [TB_CITY_PRICE] 
where ratio_sign=a.ratio_sign and city=a.city and serial_no from [TB_CITY_PRICE] as a where a.ratio_sign='1'
) as a

根据连续增长值,就很轻松的获得最大增长值了。
--up
alter table TB_CITY_PRICE add  is_max_up_follow int;--最大增长值

update a set a.is_max_up_follow=b.max_row_count
from [TB_CITY_PRICE] as a inner join (
select * 
from 
(
select max(row_count) over(partition by city)  as max_row_count,*
from (select city,serial_up_value,count(*) as row_count from [dbo].[TB_CITY_PRICE]
where serial_up_value is not null group by city,serial_up_value) as b
) as c
where c.max_row_count=c.row_count) as b
on a.city=b.city and a.serial_up_value=b.serial_up_value


最后查看结果

扫描二维码关注公众号,回复: 7291254 查看本文章

select  serial_no,* from [dbo].[TB_CITY_PRICE] where is_max_up_follow is not null  order by YM option(fast 1)


从计算结构可以看出来,价格从2009年5月连续增长4个月。

原文:大专栏  求最大的连续数


猜你喜欢

转载自www.cnblogs.com/petewell/p/11526630.html