Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have table in it two column student_number and course_number in this table the student cannot have more than 2 courses and I want to get all course_number for the the student_number in one recod in select statement in access 2007

What I have tried:

I found function in sql server 2008 it's lead but it's don't work in access 2007
Posted
Updated 23-Jun-19 1:48am
Comments
Herman<T>.Instance 24-Jun-19 6:54am    
Is there LAG/LEAD functionality in ACCESS?

That's complicated, because although you believe the student can have no more than two courses, the "real world" often doesn't work like that. If nothing else, a design where the student is assumed to only have two courses is dangerous because that is exactly the kind of thing that gets changed later. If you don't allow for it, you will make your life a lot, lot more complicated later.

It can be done - SQL Pivot: Converting Rows to Columns - The Databricks Blog[^] is intended for it - but that's complicated.

It's also possible to cheat:
SQL
SELECT StudentID, MAX(CourseNumber) AS Course1, MIN(CourseNumber) AS Course2
FROM MyTable
GROUP BY StudentID
But you can't change that later when you need three courses.

To be honest, you really need return the course list as separate rows (and sort that out in your presentation language) or return it as a comma separated list of values in a single column and deal with that in your presentation language.
You can do that in SQL Server like this:
SQL
SELECT StudentID, Courses=
   STUFF((SELECT ',' + CONVERT(VarChar(10), CourseID)
      FROM myTable b
      WHERE b.StudentID = a.StudentID
      FOR XML PATH('')), 1, 1, '')
FROM myTable a
GROUP BY StudentID 
But I have no idea if that will work in Access.
 
Share this answer
 
Well...

If you want to know, how many courses student already have, you can use COUNT():
SQL
SELECT StudentID, COUNT(CourseID) As NoOfCourses
FROM YourTable
GROUP BY StudentID

Above query returns something like this:
StudentID NoOfCourses
1         2
2         2
3         1
4         2


If you want to get row number near to course number, you can use such of query:
SQL
SELECT A.StudentID,
    (SELECT COUNT(*) FROM YourTable WHERE A.CourseID>= CourseID) AS RowNo,
    A.CourseID
FROM YourTable AS A
ORDER BY A.StudentID

Above query returns
StudentID CourseID RowNo
1         101        1
1         102        2
2         101        1
2         102        2
3         102        1
4         101        1
4         102        2


Finally, you can TRANSFORM[^] above data to this form:

StudentID 1      2
1         101    102
2         101    102
3         102    
4         101    102
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900