简体   繁体   English

表中每一行的外键值计数

[英]Foreign key value count for each row in a table

I'm trying to generate a table which returns a count for the preceding instances of the foreign key value up to and including the foreign key value on that row.我正在尝试生成一个表,该表返回外键值的前面实例的计数,直到并包括该行上的外键值。 ForeignIDValue is non-nullable. ForeignIDValue 不可为空。 I've tried table variables and common table expressions but it gets long winded and messy.我已经尝试过表变量和公用表表达式,但它变得冗长而混乱。 Is there a more elegant and concise way of doing it?有没有更优雅和简洁的方法呢?

So table A所以表A

PrimaryKeyValue ForeignIDValue  ProgressiveForeignIDValueCount
15              42              NULL
16              42              NULL
17              43              NULL
18              42              NULL
19              42              NULL
20              42              NULL
24              42              NULL
26              42              NULL
27              42              NULL
29              42              NULL
30              42              NULL
31              42              NULL
32              42              NULL
35              42              NULL
36              42              NULL
37              42              NULL
38              42              NULL
39              42              NULL
40              44              NULL
41              45              NULL
42              46              NULL
43              45              NULL

Needs to become Table B需要成为Table B

PrimaryKeyValue ForeignIDValue  ProgressiveForeignIDValueCount
15              42              1
16              42              2
17              43              1
18              42              3
19              42              4
20              42              5
24              42              6
26              42              7
27              42              8
29              42              9
30              42              10
31              42              11
32              42              12
35              42              13
36              42              14
37              42              15
38              42              16
39              42              17
40              44              1
41              45              1
42              46              1
43              45              2
SELECT PrimaryKeyValue, ForeignIDValue,
  ProgressiveForeignIDValueCount = ROW_NUMBER() OVER
    (PARTITION BY ForeignIDValue ORDER BY PrimaryKeyValue)
FROM dbo.[your table name]
ORDER BY PrimaryKeyValue, ProgressiveForeignIDValueCount;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM