Read the Aggregate (aggregate) function and Scalar (standard) function in SQL in one article

Table of contents

Foreword:

1. SQL Aggregate function

1. AVG() function

2. count() function

3. MAX() function

4. MIN() function

5. SUM() function

6. SQL GROUP BY syntax

7, SQL HAVING child clause

8. SQL EXISTS operator

9. SQL UNION operator

2. SQL Scalar function

1. SQL UCASE() function

2. SQL LCASE() function

3. SQL MID() function

4. SQL LEN() function

5. SQL ROUND() function

6. SQL NOW() function

7. SQL FORMAT() function


Foreword:

SQL has many built-in functions for counting and calculations. Broadly divided into two categories: SQL Aggregate function calculates the value obtained from the column, returns a single value. The SQL Scalar function returns a single value based on the input value.

1. SQL Aggregate function

The SQL Aggregate function calculates the values ​​obtained from columns, returning a single value.

Useful Aggregate functions:

  • AVG() - Returns the average value
  • COUNT() - Returns the number of rows
  • MAX() - returns the maximum value
  • MIN() - returns the minimum value
  • SUM() - returns the sum

1. AVG() function

The AVG() function returns the average value of a numeric column.

Get the average value from the "count" column of the "access_log" table:

SELECT AVG(count) AS CountAverage FROM access_log;

Select "site_id" and "count" with higher than average visits:

SELECT site_id, count FROM access_log
WHERE count > (SELECT AVG(count) FROM access_log);

2. count() function

The COUNT() function returns the number of rows matching the specified criteria.

The COUNT(column_name) function returns the number of values ​​for the specified column (NULLs are not counted)

SELECT COUNT(column_name) FROM table_name;

The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM table_name;

The COUNT(DISTINCT column_name) function returns the number of distinct values ​​for the specified column:

SELECT COUNT(DISTINCT column_name) FROM table_name;

Calculate the total visits for "site_id"=3 in the "access_log" table:

SELECT COUNT(count) AS nums FROM access_log
WHERE site_id=3;

Count the number of records with different site_ids in the "access_log" table:

SELECT COUNT(DISTINCT site_id) AS nums FROM access_log;

3. MAX() function

The MAX() function returns the maximum value of the specified column.

Get the maximum value from the "alexa" column of the "Websites" table:

SELECT MAX(alexa) AS max_alexa FROM Websites;

4. MIN() function

The MIN() function returns the minimum value of the specified column.

Get the minimum value from the "alexa" column of the "Websites" table:

SELECT MIN(alexa) AS min_alexa FROM Websites;

5. SUM() function

The SUM() function returns the total number of numeric columns.

Find the total count in the "count" field of the "access_log" table:

SELECT SUM(count) AS nums FROM access_log;

6. SQL GROUP BY syntax

The GROUP BY statement is used to combine the aggregation function to group the result set according to one or more columns
Count the visits of each site_id in the access_log:

SELECT site_id, SUM(access_log.count) AS nums
FROM access_log GROUP BY site_id;

Count the number of records for a site with records:

SELECT Websites.name,COUNT(access_log.aid) AS nums FROM access_log
LEFT JOIN Websites
ON access_log.site_id=Websites.id
GROUP BY Websites.name;

7, SQL HAVING child clause

The reason for adding the HAVING clause in SQL is that the WHERE keyword cannot be used with aggregate functions, and the HAVING clause allows us to filter each group of data after grouping .

After where and having are filter conditions, but there are differences:

(1) where is before group by, having is after group by

(2) Aggregation functions (avg, sum, max, min, count) cannot be placed after where as a condition, but can be placed after having

Find sites with total visits greater than 200

SELECT Websites.name, Websites.url, SUM(access_log.count) AS nums FROM (access_log
INNER JOIN Websites
ON access_log.site_id=Websites.id)
GROUP BY Websites.name
HAVING SUM(access_log.count) > 200;

Finds sites with total visits greater than 200 and alexa rank less than 200.

SELECT Websites.name, SUM(access_log.count) AS nums FROM Websites
INNER JOIN access_log
ON Websites.id=access_log.site_id
WHERE Websites.alexa < 200 
GROUP BY Websites.name
HAVING SUM(access_log.count) > 200;

8. SQL EXISTS operator

The EXISTS operator is used to determine whether the query clause has records, and returns True if one or more records exist, otherwise returns False.

Find the existence of a website with total visits (count field) greater than 200.

SELECT Websites.name, Websites.url 
FROM Websites 
WHERE EXISTS (SELECT count FROM access_log WHERE Websites.id = access_log.site_id AND count > 20

EXISTS can be used together with NOT to find records that do not match the query:

SELECT Websites.name, Websites.url 
FROM Websites 
WHERE NOT EXISTS (SELECT count FROM access_log WHERE Websites.id = access_log.site_id AND count > 200);

9. SQL UNION operator

The SQL UNION operator combines the results of two or more SELECT statements.

Note that each SELECT statement inside a UNION must have the same number of columns. Columns must also have similar data types. Also, the order of the columns in each SELECT statement must be the same.

SQL UNION syntax

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

Note: By default, the UNION operator selects distinct values. If duplicate values ​​are allowed, use UNION ALL.

SQL UNION ALL syntax

SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

Note : The column names in the UNION result set are always equal to the column names in the first SELECT statement in the UNION.

Example:

Select all distinct countries (only distinct values) from the "Websites" and "apps" tables :

SELECT country FROM Websites
UNION
SELECT country FROM apps
ORDER BY country;

Note : UNION cannot be used to list all countries in both tables. If some websites and apps are from the same country, each country will only be listed once. UNION will only pick distinct values. Please use UNION ALL to select duplicate values!

 

Use UNION ALL to select all countries from the "Websites" and "apps" tables (there are also duplicate values)

SELECT country FROM Websites
UNION ALL
SELECT country FROM apps
ORDER BY country;

Use UNION ALL to select all China (CN) data  from the "Websites" and "apps" tables (there are also duplicate values)

SELECT country, name FROM Websites
WHERE country='CN'
UNION ALL
SELECT country, app_name FROM apps
WHERE country='CN'
ORDER BY country;

 


2. SQL Scalar function

The SQL Scalar function returns a single value based on input values.

Useful Scalar functions:

  • UCASE() - Convert a field to uppercase
  • LCASE() - Convert a field to lowercase
  • MID() - Extract characters from a text field, used in MySql
  • SubString(field, 1, end) - extracts characters from a text field
  • LEN() - returns the length of a text field
  • ROUND() - rounds a numeric field to a specified number of decimal places
  • NOW() - returns the current system date and time
  • FORMAT() - Formats how a field is displayed

1. SQL UCASE() function

The UCASE() function converts the value of a field to uppercase.

Select the "name" and "url" columns from the "Websites" table and convert the value of the "name" column to uppercase:

SELECT UCASE(name) AS site_title, url
FROM Websites;

2. SQL LCASE() function

The LCASE() function converts the value of a field to lowercase.

Select the "name" and "url" columns from the "Websites" table and convert the value of the "name" column to lowercase:

SELECT LCASE(name) AS site_title, url
FROM Websites;

3. SQL MID() function

The MID() function is used to extract characters from a text field

Extract the first 4 characters from the "name" column of the "Websites" table:

SELECT MID(name,1,4) AS ShortTitle
FROM Websites;

4. SQL LEN() function

The LEN() function returns the length of the value in a text field.

Select the length of the values ​​in the "name" and "url" columns from the "Websites" table

SELECT name, LENGTH(url) as LengthOfURL
FROM Websites;

5. SQL ROUND() function

The ROUND() function is used to round a numeric field to a specified number of decimal places.

ROUND(X):  Returns the rounded integer of the parameter X.

mysql> SELECT ROUND(-1.23);
        -> -1
mysql> SELECT ROUND(-1.58);
        -> -2
mysql> SELECT ROUND(1.58);
        -> 2

ROUND(X,D):  Returns a number with D decimal places rounded to the parameter X. If D is 0, the result will have no decimal point or fractional part.

mysql> SELECT ROUND(1.298, 1);
        -> 1.3
mysql> SELECT ROUND(1.298, 0);
        -> 1

6. SQL NOW() function

The NOW() function returns the current system date and time.

Select name, url, and today's date from the "Websites" table:

SELECT name, url, Now() AS date
FROM Websites;

7. SQL FORMAT() function

The FORMAT() function is used to format the display of a field.

Select the name, url and date formatted as YYYY-MM-DD from the "Websites" table:

SELECT name, url, DATE_FORMAT(Now(),'%Y-%m-%d') AS date
FROM Websites;

 

Guess you like

Origin blog.csdn.net/m0_61243965/article/details/131510337