diff --git a/sql-queries-7/rolling-average/rolling-average-mssql.sql b/sql-queries-7/rolling-average/rolling-average-mssql.sql new file mode 100644 index 00000000..2c330802 --- /dev/null +++ b/sql-queries-7/rolling-average/rolling-average-mssql.sql @@ -0,0 +1,6 @@ +CREATE VIEW v_DailyEnrollmentWithAvg + WITH SCHEMABINDING AS + SELECT date, total_registrations, AVG(total_registrations) OVER ( ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ) + AS rolling_avg_7_days + FROM DailyEnrollment; +GO CREATE UNIQUE CLUSTERED INDEX idx_DailyEnrollmentWithAvg ON v_DailyEnrollmentWithAvg (date); diff --git a/sql-queries-7/rolling-average/rolling-average-mysql.sql b/sql-queries-7/rolling-average/rolling-average-mysql.sql new file mode 100644 index 00000000..79f07da0 --- /dev/null +++ b/sql-queries-7/rolling-average/rolling-average-mysql.sql @@ -0,0 +1,6 @@ +CREATE EVENT update_rolling_avg + ON SCHEDULE EVERY 1 DAY + DO REPLACE INTO DailyEnrollmentRollingAvg + SELECT date, total_registrations, AVG(total_registrations) OVER ( ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ) + AS rolling_avg_7_days + FROM DailyEnrollment; diff --git a/sql-queries-7/rolling-average/rolling-average-postgre.sql b/sql-queries-7/rolling-average/rolling-average-postgre.sql new file mode 100644 index 00000000..cf1ff008 --- /dev/null +++ b/sql-queries-7/rolling-average/rolling-average-postgre.sql @@ -0,0 +1,5 @@ +CREATE MATERIALIZED VIEW RollingAvgEnrollment + AS SELECT date, total_registrations, ROUND(AVG(total_registrations) OVER ( ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ), 2) + AS rolling_avg_7_days + FROM DailyEnrollment + ORDER BY date; diff --git a/sql-queries-7/rolling-average/rolling-average.sql b/sql-queries-7/rolling-average/rolling-average.sql new file mode 100644 index 00000000..af63d5c6 --- /dev/null +++ b/sql-queries-7/rolling-average/rolling-average.sql @@ -0,0 +1,4 @@ +SELECT date, total_registrations, AVG(total_registrations) + OVER ( ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ) AS rolling_avg_7_days + FROM DailyEnrollment + ORDER BY date; diff --git a/sql-queries/calculate-running-total/running-total.sql b/sql-queries/calculate-running-total/running-total.sql new file mode 100644 index 00000000..98eaac69 --- /dev/null +++ b/sql-queries/calculate-running-total/running-total.sql @@ -0,0 +1,14 @@ +SELECT id, scores, SUM(scores) +OVER (ORDER BY id) AS RunningTotal +FROM Exam; + + +SELECT id, scores, (SELECT SUM(scores) + FROM Exam e2 WHERE e2.id <= e1.id) AS RunningTotal +FROM Exam e1 ORDER BY id; + + +SELECT s1.id, s1.scores, SUM(s2.scores) AS RunningTotal +FROM Exam s1 +JOIN Exam s2 ON s1.id >= s2.id +GROUP BY s1.id, s1.scores ORDER BY s1.id;