0

Taking a course in databases and i am unsure of how to create this view. I have this table(postgresql):

CREATE TABLE InQueue (
  id INT REFERENCES Student(id),
  course VARCHAR(10) REFERENCES RestrictedCourse(course_code),
  since TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id,course),
  UNIQUE (course,since)
  );

I am supposed to create a view that lists course, id, number, where number is calculated with since. Basically the lowest since gives the queuenumber 1, the 2nd lowest gives 2 and so forth. (course,number) is unique, but not number by itself, since there are many different courses.

What i think needs to be done is to first order the table by (course,since) and then just add sequence numbers, but eventually the course will change and then the sequence numbers need to start over, beginning with 1 again.

Could someone point me in the right direction? :)

1
  • You should look into window functions and then in particular on partitioning the data into groups and how to apply a window function over them. Commented Feb 24, 2016 at 17:05

1 Answer 1

2

Use:

Select row_number() over (partition by course order by since asc) as yournumber, id,
course, since from InQueue 

You can read about analytic functions here: http://www.postgresql.org/docs/9.4/static/tutorial-window.html

Sign up to request clarification or add additional context in comments.

5 Comments

Perfect, this produces the desired result. I'll read up on what all those keywords do and add this to my work. Super! edit -- thanks for the link, reading right now.
I added a link to explain analytic functions (like row_number here)
@Rewbert You should not read the referenced documentation. Version 8.4 is prehistoric and upsupported since mid 2014. Read the current documentation instead.
Oh okay, thanks for the tip. Will make sure to find updated documentation :)
@Patrick the content I posted in the link remains unchanged though.

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.