...
Code Block |
---|
SELECT Course, SUM(FTE) AS TotalFTE, SUM(1) AS TotalStudents FROM Students GROUP BY Department |
Course | ||
---|---|---|
Biology | 1.5 | 2 |
Archaeology | 1 | 1 |
Politics | 1 | 1 |
...
We have a code in our Students table so we need to relate it to its lookup, Country:
02 | England |
05 | France |
06 | Wales |
14 | Germany |
...
Code Block |
---|
SELECT Students.Surname, Students.Forename, Country.CountryName FROM Students INNER JOIN Country ON Students.Country = Country.CountryCode |
gives:
Surname | Forename | |
---|---|---|
Smith | John | England |
Cooper | Brian | France |
Wertz | Heidi | Germany |
...
Code Block |
---|
SELECT Students.Surname, Students.Forename, Country.CountryName FROM Students LEFT JOIN Country ON Students.Country = Country.CountryCode |
gives:
Surname | Forename | |
---|---|---|
Smith | John | England |
Cooper | Brian | France |
Wertz | Heidi | Germany |
Goodman | Pete |
|
...
Code Block |
---|
SELECT Country, SUM(1) AS TotalStudents FROM Students GROUP BY Country |
gives:
Country | |
---|---|
02 | 1 |
03 | 2 |
19 | 450 |
16 | 103 |
Then wrap this in brackets and use it in your FROM clause:
Code Block |
---|
SELECT Country.CountryName, StuCount.TotalStudents FROM ( SELECT Country, SUM(1) AS TotalStudents FROM Students GROUP BY Country ) StuCount LEFT JOIN Country ON Students.Country = Country.CountryCode WHERE StuCount.TotalStudents >= 100 |
gives:
Bulgaria | 450 |
Micronesia | 103 |
Nesting is a powerful way to take oodles of big data, perform a sequence of steps on it, in order to squish it down into exactly the simple form you want. It's also a superfast way to get lost in onion layers of logic and make small mistakes that are obscured until a few years later when something new crops up and breaks things.
...
This is about as far as you can get with the standard SQL syntax. Despite agreements all round, database vendors have decided they know best and have their own implementation of things that are so common across the world that you sometimes can't believe it. Say you want the last character of a value (we often do, as we keep programme length in this place of many codes).
Microsoft SQL Server / MySQL
Code Block |
---|
SELECT RIGHT(ProgrammeCode,1) |
...