So I’m going through Stanford’s DB class, and on one of the questions we are given the following database. Now, I’ve already gotten my code to work, but it strikes me as terribly inefficient. We’re using SQLite to execute our queries.
Is there any way I can write the following in a more fluid and readable manner? Specifically, I hate having to copy and paste my Averages table in twice.
The following isn’t exact code per se because I don’t want to break honor code. However, I have an Averages table, and everywhere where Averages shows up below, I am literally copy and pasting the entire SELECT query. Is there any way to avoid this?
SELECT avgbefore-avgafter
FROM
(SELECT avg(avgs) as avgbefore
FROM
Averages
WHERE year < 1980) as Before,
(SELECT avg(avgs) as avgafter
FROM
Averages
WHERE year >= 1980) as After
I don’t know if SQLite supports the ANSI CASE statement, but if it does try the following:
This uses the fact that NULL values are not taken into account by aggregate functions.