Question

I have scenario, where I have to give sequence number for each record. And the sequence number should re-initialized to initial value if it is different account.

I was trying like this

declare @account_no varchar(50)
declare @seq_no int
declare @temp_no int
set @temp_no=1

select 
    (@account_no = (CASE WHEN @account_no <> PN.vst_int_id 
                           THEN PN.vst_int_id
                    END))
    ,(@seq_no = (CASE WHEN @account_no = PN.vst_int_id 
                        THEN @temp_no + 1
                      ELSE 1
                 END))
   ,@seq_no
   ,nte_pri_cd 
from 
   TSM310_PATIENT_NOTES PN
where 
   vst_int_id = '4588611'
Was it helpful?

Solution

Good news we have Ranking Functions in sql server to make these kind of operations very simple. Note it is only available in Sql Server 2005 and later editions.

select *,
       ROW_NUMBER() OVER (PARTITION BY AccountID ORDER BY SomeColumn) SequenceNumber

from TSM310_PATIENT_NOTES PN
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top