我想添加一个名为PLRowNo的列,它是每个凭证组中PL acttype的行号。我还希望每个凭证编号的编号从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 |
您不需要临时表或古怪的更新,只需使用ROW_NUMBER
即可
SELECT *,
PLRow_no = CASE WHEN actype = 'PL' THEN
ROW_NUMBER() OVER (PARTITION BY actype, voucherID ORDER BY id)
END
FROM tbl_tmp
ORDER BY id;
db<gt;小提琴
请尝试一下。
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