美文网首页
Aggregate functions

Aggregate functions

作者: 腾子_Lony | 来源:发表于2017-08-26 20:34 被阅读0次

Often, you will want to perform some calculation on the data in a database. SQL provides a few functions, called aggregate functions, to help you out with this.

For example,

SELECT AVG(budget)

FROM films;

gives you the average value from the budget column of thefilmstable. Similarly, the MAX function returns the highest budget:

SELECT MAX(budget)

FROM films;

The SUM function returns the result of adding up the numeric values in a column:

SELECT SUM(budget)

FROM films;

You can probably guess what the MIN function does! Now it's your turn to try out some SQL functions.

In addition to using aggregate functions, you can perform basic arithmetic with symbols like+ , -, *,  and / .

So, for example, this gives a result of12:

SELECT (4 * 3);

However, the following gives a result of1:

SELECT (4 / 3);

What's going on here?

SQL assumes that if you divide an integer by an integer, you want to get an integer back. So be careful when dividing!

If you want more precision when dividing, you can add decimal places to your numbers. For example,

SELECT (4.0 / 3.0) AS result;

gives you the result you would expect:1.333.

To avoid situations like this, SQL allows you to do something calledaliasing. Aliasing simply means you assign a temporary name to something. To alias, you use the AS keyword, which you've already seen earlier in this course.

For example, in the above example we could use aliases to make the result clearer:

SELECT MAX(budget) AS max_budget,

MAX(duration) AS max_duration

FROM films;

相关文章

网友评论

      本文标题:Aggregate functions

      本文链接:https://www.haomeiwen.com/subject/zbjvdxtx.html