SQL生成每个组内的序列号

标签 sql sql-server t-sql

 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/

相关文章:

mysql - IF() 函数内的子查询

sql-server - 更改 SQL Server 2012 数据库的排序规则

sql获取按另一列分组的重复列值

sql-server - FREETEXTTABLE 为什么或如何给出比其他人更高的排名值

sql - Oracle PL/SQL - 如何删除 SQL 表中的多条重复记录?

mysql - 在内部连接Mysql中找到最近的时间

php - 如果存在则更新否则插入。 MySQL-PHP

sql-server - 如何使用 SQL Server 中的隐藏数据库对象?

c# - 远程交易

sql - 谁被叫了?