【发布时间】:2021-02-01 10:47:41
【问题描述】:
我有一个 SQL (SQL Server) 语句 SELECT id, animalId, ownerId FROM myTable ORDER BY id,它输出以下数据:
id | animalId | ownerId
------------------------
1 | 123 | 62
2 | 123 | 182
3 | 240 | 27
4 | 2 | 30
5 | 73 | 35
6 | 123 | 62
7 | 108 | 162
8 | 2 | 30
9 | 2 | 30
10 | 73 | 35
我想要做的是动态添加第四列,作为每行的计数器,这些行具有相同的 animalId 和 ownerId 值。所以结果输出是:
id | animalId | ownerId | iterator
-----------------------------------
1 | 123 | 62 | 1 <-- First instance where animalId is 123 and ownerId is 62
2 | 123 | 182 | 1
3 | 240 | 27 | 1
4 | 2 | 30 | 1
5 | 73 | 35 | 1
6 | 123 | 62 | 2 <-- Second instance where animalId is 123 and ownerId is 62
7 | 108 | 162 | 1
8 | 2 | 30 | 2
9 | 2 | 30 | 3
10 | 73 | 35 | 2
谁能告诉我如何解决这个问题?
非常感谢。
【问题讨论】:
标签: sql sql-server distinct-values