我想给CardId和InvoiceNo的每个组合提供以下数据的数字/等级
;WITH Test (CardId,InvoiceNo,Category,Amount) as
(
SELECT '1001','3001','Fees',30
UNION ALL SELECT '1001','3001','Non-Fees',45
UNION ALL SELECT '1001','3001','Service Fees',55
UNION ALL SELECT '1002','3002','Fees',10
UNION ALL SELECT '1002','3002','Non-Fees',25
UNION ALL SELECT '1002','3002','Service Fees',10
UNION ALL SELECT '1003','3010','Fees',45
UNION ALL SELECT '1003','3010','Non-Fees',70
)
喜欢这个
CardId InvoiceNo Amount Rank
1001 3001 30 1
1001 3001 45 1
1001 3001 55 1
1002 3002 10 2
1002 3002 25 2
1002 3002 10 2
1003 3010 45 3
1003 3010 70 3
我使用Row_number()
和Rank()
尝试了以下查询,但未给出我想要的结果。 rank()
将所有行排名为1,row_number()
将每个组编号为1,2,3。
SELECT CardId
,InvoiceNo
,Amount
,RANK() OVER (PARTITION BY CardID,InvoiceNo ORDER BY CardId) as RankNo
FROM Test
答案 0 :(得分:4)
删除分区。 rank函数在分区中查找分区,其中新分区重置排名。因此,它看到每个分区中的每条记录都与第一条相关。此外,您可能需要dense_rank()
。
SELECT CardId
,InvoiceNo
,Amount
,DENSE_RANK() OVER (ORDER BY CardId, InvoiceNo) as RankNo
FROM Test
ORDER BY CardId, InvoiceNo, Amount
小提琴:
答案 1 :(得分:2)
试试这个。我认为这就是你要找的东西。
SELECT CardId
,InvoiceNo
,Amount
,DENSE_RANK() OVER (ORDER BY CardId, InvoiceNo) as RankNo
FROM Test