简体   繁体   English

SQL脚本自动递增,具体取决于列值

[英]SQL Script to Auto Increment Depending on Column Value

This may be tricky. 这可能很棘手。 I have an xlsx file with sets of rows that have one similar column value. 我有一个xlsx文件,其中xlsx具有相似列值的行。 The issue is that the client did not give me the correct values for another column (the column does not exist). 问题是客户端没有为我提供另一列的正确值(该列不存在)。 I need to auto increment a new column based on the value in the other column. 我需要根据另一列中的值自动增加一个新列。 When the value of the column changes, the incremented var needs to go back to 0. 当列的值发生更改时,递增的var需要返回0。

EX: EX:

Current
C1 | C2 | 
1  | A  |
2  | A  |
3  | A  |
4  | B  |
5  | B  |

Desired
C1 | C2 | C3 (NEW)
1  | A  | 0
2  | A  | 1
3  | A  | 2
4  | B  | 0
5  | B  | 1

Is it possible to do this through SQL? 是否可以通过SQL执行此操作? Is there a better way to do this in Excel or Access? 有没有更好的方法在Excel或Access中执行此操作?

This is very possible with SQL, here is a SQL Fiddle , and here is the content of that fiddle: 这很可能用SQL,这里是一个SQL小提琴 ,这里是小提琴的内容:

CREATE TABLE a
(
  C1 INT,
  C2 VARCHAR(10)
)

GO

INSERT INTO a VALUES (1, 'A')
INSERT INTO a VALUES (2, 'A')
INSERT INTO a VALUES (3, 'A')
INSERT INTO a VALUES (4, 'B')
INSERT INTO a VALUES (5, 'B')

SELECT C1, C2,
  ROW_NUMBER() OVER (PARTITION BY C2 ORDER BY C1) - 1 AS C3
FROM a

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

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