質問

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'
役に立ちましたか?

解決

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top