Calculate with SQL statistics

In 99% of cases, SQL is used to store and read data from a database. However, very few know that SQL can also be used to perform complex statistical calculations.

History

In 1970, relational databases were mentioned for the first time. Their development away from step-by-step programming towards a declarative, math-like expression for calculating with data led to rapid developments in data processing. Suddenly, the use of data was separated from its storage. While the application handles what happens to the data and what it means, the database system organizes itself by optimizing storage structures, creating indexes, and rewriting and optimizing query plans. In this way, one develops statistical formulas once, and subsequently, any SQL-capable database system can calculate them. If, for example, the data volumes become larger, one can consider a commercial DBMS.

The Group Operator

With the GROUP BY clause of SQL, individual data records are sorted into categories. The Group operator is the basis for all statistics because it aggregates data records. With the grouping expression, you specify by which characteristic the data records are grouped. The probability P(A | B) is calculated with, for example, with SELECT .... GROUP BY B. The grouping expression can contain both columns (for example, group turnover by category), but also calculations (group by time of day of the order date, group by day of the week, group by turnover under and over €1,000).

The SUM and COUNT Operators

Sums are suitable for enabling size comparisons of numerical values. For example, the turnover of a department can be summed up. Counting is exactly the same, except that a 1 is added up each time.

The Holy Grail: AVG

With the AVG function, one normally calculates averages, for example, the average salary of a department. However, we statisticians can do much more with it. If you measure, for example, the average of a boolean expression, a percentage can be calculated. Example: SELECT AVG(Alter < 18) FROM Besucher calculates what proportion of the visitors are under 18 years old. Particularly in probability theory, the AVG operator is essential, because one can express Bayes' theorem perfectly in SQL by simply calculating the average of all probabilities grouped by the condition. What can be achieved with this, you can read about in the post about probabilities read further.
Categorias
Etiquetas