📜  SQLite aggregate函数(1)

📅  最后修改于: 2023-12-03 15:05:19.800000             🧑  作者: Mango

SQLite Aggregate Functions

SQLite provides aggregate functions to perform calculations on a set of values and return a single result. These functions are useful for summarizing data or generating reports in SQL queries. Here's an introduction to SQLite aggregate functions that every programmer should know.

1. COUNT

The COUNT function is used to count the number of rows in a table or a result set based on a specified condition. It can be used with the * wildcard to count all rows or with specific column names.

SELECT COUNT(*) FROM table_name;
SELECT COUNT(column_name) FROM table_name;
SELECT COUNT(column_name) FROM table_name WHERE condition;

2. SUM

The SUM function calculates the sum of all values in a specified column. It is commonly used with numerical data types, such as integers or decimals.

SELECT SUM(column_name) FROM table_name;
SELECT SUM(column_name) FROM table_name WHERE condition;

3. AVG

The AVG function calculates the average (mean) of all values in a specified column. It is also used with numerical data types.

SELECT AVG(column_name) FROM table_name;
SELECT AVG(column_name) FROM table_name WHERE condition;

4. MIN

The MIN function returns the minimum value from a specified column. It can be used with various data types such as numbers, dates, or strings.

SELECT MIN(column_name) FROM table_name;
SELECT MIN(column_name) FROM table_name WHERE condition;

5. MAX

The MAX function returns the maximum value from a specified column. Just like MIN, it can be used with different data types.

SELECT MAX(column_name) FROM table_name;
SELECT MAX(column_name) FROM table_name WHERE condition;

6. GROUP_CONCAT

The GROUP_CONCAT function concatenates values from a column into a single string, where multiple values are separated by a delimiter. It is often used in combination with the GROUP BY clause to generate comma-separated lists.

SELECT GROUP_CONCAT(column_name) FROM table_name;
SELECT GROUP_CONCAT(column_name SEPARATOR ', ') FROM table_name;
SELECT column_name, GROUP_CONCAT(other_column) FROM table_name GROUP BY column_name;

These are some of the commonly used aggregate functions in SQLite. They can be combined with other SQL clauses like WHERE, HAVING, and ORDER BY to perform more complex calculations and generate meaningful results.

Remember to refer to the SQLite documentation for more details on each aggregate function and their specific usage. Happy querying!