I would recommend you to refer the below links to learn SQL. Then go through the above solution given by Pete. That should give you an idea on how to approach your problem.
SQL Tutorial[
^]
SQLCourse.com[
^]
You can find more resources on SQL in
Google[
^] or you can refer to beginner articles on SQL in CP
here[
^]