简体   繁体   中英

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. 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.

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? Is there a better way to do this in Excel or Access?

This is very possible with SQL, here is a SQL Fiddle , and here is the content of that fiddle:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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