I have a table with below structure.
I am not having control over changing the table.
It has three columns: student_name, student_id, name_id
Now student name could be any number of words. Exactly one word will come in one row. Based on the number of words, name_id will be entered and the student_id will be repeated.
The structure would be some thing like:
say name1 is: Ram Laxman Prasad Sharma
and name2 is: Pandit Gangadhar Vidyadhar Mayadhar Omkarnath Shastri
So the table will look like:
student_name | student_id | name_id
-------------------------------------------------
Ram 1 1
Laxman 1 2
Prasad 1 3
Sharma 1 4
Pandit 2 1
Gangadhar 2 2
Vidyadhar 2 3
Mayadhar 2 4
Omkarnath 2 5
Shastri 2 6
I hope I explained the structure clearly.
Now, I want to write a query to read only first four names per student. However, if the number of names is less then four, empty string should go and if its greater then four, first four should go and rest just ignored.
I need to put it in a single select query only, since this query will be passed in a spring batch program. But I am not getting how to loop through nameid column to take first four name id for every student.
How to design this sql for DB2 database v8??
Thanks for reading.
improved version inspired by Amit – if you need all 4 names in 1 column 🙂