我有一种情况,即在指定的时间内对帐户应用折扣,然后更改回原始折扣。
Disount Date
10 1/1/2013
10 1/2/2013
20 1/3/2013
20 1/4/2013
20 1/5/2013
10 1/6/2013
10 1/7/2013
我希望通过逐步计算来识别更改
Disount Date Identify
10 1/1/2013 1
10 1/2/2013 1
20 1/3/2013 2
20 1/4/2013 2
20 1/5/2013 2
10 1/6/2013 3
10 1/7/2013 3
我试过了:
DECLARE @groupercount int
SET @groupercount = 1
并在使用的案例陈述中:
when <whatever> then @groupcount
else @groupcount +1
这只会在识别列中产生1或2,它不会增加到3,4,5等等。
有什么想法吗?
答案 0 :(得分:1)
您似乎想要将折扣相同的期间(基于日期)相加。您的语法类似于SQL Server语法。以下是SQL Server 2012语法(这也适用于Postgres和Oracle):
select t.discount, t.date,
(sum(NewPeriodStart) over (order by date)) as Identify
from (select t.*,
(case when t.discount = lag(t.discount) over (order by date) then 0 else 1
end) as NewPeriodStart
from t
) t;
如果您没有lag()
和累计sum()
,您仍然可以使用row_number()
和基本窗口函数执行此操作:
select discount, date, dense_rank() over (partition by groupid order by mindate) as Identify
from (select t.*, min(date) over (partition by groupid) as mindate
from (select t.*,
(row_number() over (order by date) -
row_number() over (partition by discount order by date)
) as groupid
from t
) t
) t;