[英]How to apply row_number for each partition with condition
我想添加一個名為 PLRowNo 的列,它是每個憑證組中 PL actype 的行號。 我還希望每個憑證號的編號從 1 開始。
這是預期的結果
| id | voucherID | actype | PLRowNo |
|----|-----------| -------|---------|
| 1 | voucher01 | BS | |
| 2 | voucher01 | PL | 1 |
| 3 | voucher01 | BS | |
| 4 | voucher01 | PL | 2 |
| 5 | voucher01 | PL | 3 |
| 6 | voucher01 | BS | |
| 7 | voucher01 | PL | 4 |
| 8 | voucher01 | BS | |
| 9 | voucher01 | PL | 5 |
| 10 | voucher02 | PL | |
| 11 | voucher02 | PL | 1 |
| 12 | voucher02 | BS | |
| 13 | voucher02 | PL | 2 |
這是我嘗試過的:
CREATE TABLE tbl_tmp (
id int not null primary key,
voucherID nvarchar(10) not null,
actype nvarchar(10) not null
);
insert into tbl_tmp(id,voucherID, actype)
values (1,'voucher01', 'BS'),
(2,'voucher01', 'PL'),
(3,'voucher01', 'BS'),
(4,'voucher01', 'PL'),
(5,'voucher01', 'PL'),
(6,'voucher01', 'BS'),
(7,'voucher01', 'PL'),
(8,'voucher01', 'BS'),
(9,'voucher01', 'PL'),
(10,'voucher02', 'PL'),
(11,'voucher02', 'PL'),
(12,'voucher02', 'BS'),
(13,'voucher02', 'PL')
select *,0 as PLRowNo into #tmp from tbl_tmp
declare @id int set @id=0
update #tmp
set @id= case when actype ='PL' then @id+1 else 0 end,
PLRowNo = case when actype='PL' then @id else 0 end
select * from #tmp
這個查詢的問題是,如果前一行的類型是“BS”,即使在同一個憑證分區中,它也會從 1 (id: 13) 開始計數。 我希望在一張憑證內繼續。
這是錯誤的結果
| id | voucherID | actype | PLRowNo |
|----|-----------| -------|---------|
| 1 | voucher01 | BS | |
| 2 | voucher01 | PL | 1 |
| 3 | voucher01 | BS | |
| 4 | voucher01 | PL | 2 |
| 5 | voucher01 | PL | 3 |
| 6 | voucher01 | BS | |
| 7 | voucher01 | PL | 4 |
| 8 | voucher01 | BS | |
| 9 | voucher01 | PL | 5 |
| 10 | voucher02 | PL | |
| 11 | voucher02 | PL | 1 |
| 12 | voucher02 | BS | |
| 13 | voucher02 | PL | 1 |
請試試這個。
select *,
CASE
WHEN actype='PL' THEN CAST((select count(*) from tbl_tmp as t where actype='PL' and t.id<=tbl_tmp.id and t.voucherID=tbl_tmp.voucherID )as VarChar(10))
ELSE ''
END
as PLRowNo
from tbl_tmp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.