I’m totally new to SQL so I guess my question is quite simple but I wasn’t able so far to peform the desired output by myself.
I did a survey and asked 3 people to solve assignment A (with 3 tasks) and 3 people to solve assignment B (with 3 tasks).
And then I made a table which looks like this:
Table: Results
+---------+---------+---------+---------+---------+
| ID | AssgnID | Answer1 | Answer2 | Answer3 |
+---------+---------+---------+---------+---------+
| 1 | A1 | 20 | 45 | 80 |
| 2 | A1 | 22 | 40 | 82 |
| 3 | A1 | 25 | 39 | 85 |
| 4 | A2 | 45 | 10 | 75 |
| 5 | A2 | 50 | 15 | 72 |
| 6 | A2 | 50 | 12 | 80 |
+---------+---------+---------+---------+---------+
What I now want to do is, to show for AssgnID A1 and A2 all the Answers in one row like this:
Table: Results per AssgnID
+---------+---------+---------+---------+---------+--------+---------+---------+--------+---------+---------+
| ID | AssgnID | Answer1 | Answer2 | Answer3 |Answer4 | Answer5 | Answer6 |Answer7 | Answer8 | Answer9 |
+---------+---------+---------+---------+---------+---------+---------+---------+-------+---------+---------+
| 1 | A1 | 20 | 45 | 80 | 22 | 40 | 82 | 22 | 40 | 82
| 2 | A2 | 45 | 10 | 75 | 50 | 15 | 72 | 50 | 12 | 80
+---------+---------+---------+---------+---------+---------+---------+---------+-------+---------+---------+
I’m able to show the distinct AssgnID by using DISTINCT or GROUP BY but I can’t show all the results in the same output.
Do I have to try something with a JOIN?
I appreciate your help a lot. thanks
If you are willing to accept your list of answers as a comma-separated list rather than actual columns, you can use PostgreSQL’s
string_agg()to force them into a list by concatenating the three answer columns from each row into a unit, then grouping all of those together:Would produce:
If you need to perform additional SQL operations, however, the best course of action and best permanent solution is to redesign your table structure to store these answers in a normalized way. This method defines the survey in one table, and another table holds one row per answer, or three rows per
SurveyID.Table Surveys
Table Answers