3

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?

1
  • Which version of SQL? Commented Dec 4, 2013 at 3:47

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.