Common SQL functions
- avg() The
avg() function returns the average value of a numeric column.
select avg(count) as CountAverage from access_log;
- count() The
count() function returns the number of rows that match the specified conditions.
-- COUNT(column_name) 函数返回指定列的值的数目(NULL 不计入)
select count(column_name) from table_name;
-- COUNT(*) 函数返回表中的记录数:
select count(*) from table_name;
-- COUNT(DISTINCT column_name) 函数返回指定列的不同值的数目:
select count(distinct column_name) from table_name;
- max() The
max() function returns the maximum value of the specified column.
select max(column_name) from table_name;
- min() The
min() function returns the minimum value of the specified column.
select max(column_name) from table_name;
- sum() The
sum() function returns the total number of numeric columns.
select sum(column_name) from table_name;
- The group by
GROUP BY statement is used to combine aggregate functions to group the result set based on one or more columns.
select site_id, sum(count) as nums from access_log group by site_id;
- The
reason for having increased the having clause in SQL is that the WHERE keyword cannot be used with aggregate functions. The having clause allows us to filter each group of data after grouping.
-- 现在我们想要查找总访问量大于 200 的网站。
select Websites.name, Websites.url, sum(access_log.count) as nums
from access_log inner join Websites on Websites.id = access_log.site_id
group by Websites.name
having sum(access_log.count) > 200;
-- 现在我们想要查找总访问量大于 200 的网站,并且 alexa 排名小于 200。
select Websites.name, Websites.url, sum(access_log.count) as nums
from access_log inner join Websites on Websites.id = access_log.site_id
where Websites.alexa < 200
group by Websites.name
having sum(access_log.count) > 200;