PO NO Acc No ResultSeqNo A1 12 1 A1 12 1 A1 12 1 A1 12 1 A2 12 2 A2 12 2 A2 12 2 A3 13 1 A3 13 1 A4 13 2 A4 13 2 A5 14 1
In above table, PONO
and AccNo
are related, SeqNo
is nothing but the Counter in the flag. I need to group by PONo
and Accno
.
If you see in the above table, A1
and A2
has same account number , but all A1
is considered to be a single group, so the seqNo should be 1 for all A1
.
A2
also has the same acc no as A1
, but it's a different group, so it should have the seq No 2.
Put another way: for each AccNo
number, I need to generate sequence numbers by PO NO
. So for Account #12, all of the A1
PO NO records have sequence 1, and all of the A2
PO NO records have sequence 2. For account 13, A3 is 1 and A4 is 2.
Here is what I have so far:
UPDATE x
SET x.ResultSeqNo = x.dr
FROM
(
SELECT SeqNo,dense_rank() over (order by PO NO) as dr
FROM [Purchaseorder]
WHERE status = 'In'
) x
最佳答案
您需要使用dense_rank
分析函数,但添加一个partition by
子句来对集合进行分组以生成序列号,例如:
SELECT dense_rank() OVER (PARTITION BY acc_no ORDER BY po_no)
关于SQL生成每个组内的序列号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40245580/