1

Assume that we have a table like this:

Date User Item
2021-01-01 A X
2021-01-05 A Y
2021-01-11 A Z
2021-01-01 B X
2021-01-16 B Y
2021-01-01 C X
2021-01-02 C Y
2021-01-03 C Z
2021-01-10 D X
2021-01-15 D Y

I want to group each user by its date and item and add sequence number DURING QUERY, NOT BY MODIFYING TABLE. For a user, the sequence number of the item with the first date should be first. The number should start all over again for each new user. I want to retrieve data like this:

Date User Item Sequence
2021-01-01 A X 1
2021-01-05 A Y 2
2021-01-11 A Z 3
2021-01-01 B X 1
2021-01-16 B Y 2
2021-01-01 C X 1
2021-01-02 C Y 2
2021-01-03 C Z 3
2021-01-10 D X 1
2021-01-15 D Y 2

Is it possible? Can I retrieve data like that?

Thanks!

1
  • 1
    Tag your question with the database you are using. Commented Jun 8, 2021 at 15:26

1 Answer 1

3

This is what row_number() does:

select t.*,
       row_number() over (partition by user order by date) as seqnum
from t;
Sign up to request clarification or add additional context in comments.

1 Comment

I also used row_number() but the key part that I missed is "partition by". Thanks!

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.