Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.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_Sqlite - Fatal编程技术网

Sql 表列中的计数值更改

Sql 表列中的计数值更改,sql,sqlite,Sql,Sqlite,考虑一个根据id排序的表。如何计算“value”列中值的更改数?在以下示例中,更改的数量为3 10到20、20到10、10到30。Thx id value 1 10 2 10 3 20 4 20 5 10 6 30 7 30 您可以使用相关子查询来识别更改。然后把它们加起来。当该值与以前的值不同时,会发生更改: select count(*) from (select t.*, (

考虑一个根据id排序的表。如何计算“value”列中值的更改数?在以下示例中,更改的数量为3 10到20、20到10、10到30。Thx

id value 1 10 2 10 3 20 4 20 5 10 6 30 7 30
您可以使用相关子查询来识别更改。然后把它们加起来。当该值与以前的值不同时,会发生更改:

select count(*)
from (select t.*,
             (select value
              from table t2
              where t2.id < t.id
              order by t2.id desc
              limit 1
             ) as prev_value
      from table t
     ) t
where prev_value <> value;

如果ID是连续的,没有间隙

Select count(*)
From table t1
   join table t2 
       on t2.id = t1.id + 1
where t2.value <> t1.value
否则

Select count(*)
From table t1
   join table t2 
       on t2.id = (Select min(id)
                   From table 
                   where id > t1.id)
where t2.value <> t1.value

我喜欢使用这个功能:导入。例如,如果您有此选项,请选择:

select id, value
from youTable
where id <= 7
我用lead函数找到value列的下一个值,并与当前值进行比较,因此:

select count(1) as number from
   (select lead(value) over(order by id) as nextValue, id, value
    from youTable
    where id <= 7) as tmp
where tmp.nextValue <> tmp.value

现在,在数字中,我将数值转换为数值列

我有点困惑,什么是表t2和t,我只有一个输入表?@dousin。这些是表别名,是表的缩写,可以进行自连接。这很好用!有没有办法将“计数过程”添加为一个单独的列,可以与原始数据集一起显示?i、 e.有一个包含三列| id | value | count |的表,并且在每一行中,计数都是到目前为止最新的计数。
select count(1) as number from
   (select lead(value) over(order by id) as nextValue, id, value
    from youTable
    where id <= 7) as tmp
where tmp.nextValue <> tmp.value