Sorry that this is not really VBA question, I just use it inside VBA code.
Just making up a simple database table. The real database table is much more complex with many more fields.
Database: MS S-Q-L (I modified S-Q-L, since the term is blocked by system)
Column A-D: Database table structure (just making up a simple example).
StudentID is unique, which represents an individual.
Unknown: I don't know how many subjects are there.
Yellow area is desired output format, something like pivot table.
Note: It is possible that StudentID 111 took Math test in 2023 but not in 2024, in this case, cell J7 should be blank.
Note: It is also possible that studentID 112 does not take math test in either 2023 or 2024, while other students take math test. In this case, cell I8 and J8 should be blank.
Goal: I would like to identify large score change from previous year for each student's each subject. I want to pull data into excel sheet in yellow area format, so that I can write other part of VBA code.
I already know connection string to database. If I use below code to pull data from database table, the output data will be something like column A:D data. I know how to do this part of task with below VBA code.
Question: How can I modify TestScoreQuery so that output data will be something like yellow area?
Reference: https://www.w3schools.com/sql/sql_groupby.asp
Edit: As mentioned, it is just a simple sample. You can assume that there are many StudentID and many subjects, in real database table, there could be hundreds of subjects associated to each student, and there are multiple years too. if I use my code, excel sheet may not fit, since there are only 1,048,576 rows. I would like to have only one row for each StudentID, as yellow area output format.
Actually, I should add Where Year = 2003 or 2004 in below code TestScoreQuery, I have not figured out how to write it correctly, I should limit the code to two specific years, comparing current year to previous year. But this is not main question, the main question is how to write the code and make output as pivot table format.
SQL Groupby.jpg![]()
Please Login or Register to view this content.
SQL Output.xlsx
Bookmarks