根据具有共享数据的某些列创建标识符

时间:2018-07-26 02:33:35

标签: sql-server-2008 tsql

在下面的示例中,列sequence应该是在某些列中共享相同值的行的标识符-compania, hrEntr, hrSaida, durJornada, durInterv, iniInterv, termInterv, sistema_horario, turno-但是,不应将其中的列之一计算在内{ {1}}。

因此,如图所示,前五行共享这些列,因此dia应该为1。第6行(不共享所有先前的值)应该拥有自己的sequence号设置为2。

enter image description here

我使用过sequence,但是它会产生相反的结果,即匹配列停止时重新开始。

有没有一种方法可以创建我想要的结果?

1 个答案:

答案 0 :(得分:1)

您可以使用RANK()函数。检查是否可以解决您的需求:

drop table if exists stackoverflowTbl;
/********************************************************** DDL+DML */
create table stackoverflowTbl(id int identity (1,1), txt int)
GO
insert stackoverflowTbl (txt) values (1),(1),(2),(1),(3),(22),(22)
GO
select * from stackoverflowTbl
GO
/********************************************************** solution */
select id,txt,
    ROW_Number () OVER (order by txt) - RANK ( ) OVER ( partition by txt order by id ) as MySequence 
from stackoverflowTbl
GO