Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
以SQL中的增量计数_Sql_Increment - Fatal编程技术网

以SQL中的增量计数

以SQL中的增量计数,sql,increment,Sql,Increment,我有一种情况,在一段特定的时间内对一个帐户应用折扣,然后又改回原来的折扣 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

我有一种情况,在一段特定的时间内对一个帐户应用折扣,然后又改回原来的折扣

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
when then@groupcount
else@groupcount+1
这只会在标识列中产生1或2,不会增加到3、4、5等等


有什么想法吗?

您似乎想将折扣相同的时段相加(基于日期)。您的语法看起来像SQL Server语法。以下是SQL Server 2012语法(这也适用于Postgres和Oracle):

如果您没有
lag()
和累计
sum()
,您仍然可以使用
row\u 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;

您使用的数据库管理系统和版本是什么?SQL Server、mySQL等。
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;