SQL:计算列值与前一行相比发生更改的行数
假设我有Oracle或Postgresql数据库SQL:计算列值与前一行相比发生更改的行数,sql,oracle,postgresql,Sql,Oracle,Postgresql,假设我有Oracle或Postgresql数据库 ID IdExample OrderByColumn What I want ---------- ---------- ---------- ---------- 1 1 1300 1 2 1 2450 1
ID IdExample OrderByColumn What I want
---------- ---------- ---------- ----------
1 1 1300 1
2 1 2450 1
3 2 5000 2
4 2 4800 2
5 1 5100 3
6 1 6000 3
7 4 7000 4
8 1 8000 5
如何计算idExample中的更改?数据按OrderByColumn排序
我需要输出由我想要的内容表示的新列
注意IdExample中的1。它会重复,但我想重复。
当表有成千上万条记录时,查询应该快速执行
谢谢您需要使用滞后和求和分析函数,如下所示:
Select t.*,
sum(case when lg is null or lg <> idexample then 1 else 0 end)
over (order by id) as result
from
(Select t.*,
lag(idexample) over (order by id) as lg
From your_table t) t