Basic usage of commonly used functions and window functions in MySQL
1. Basic functions
1. Aggregation function:
SELECT COUNT(*) FROM table_name;
: Counts the number of rows in the table.SELECT SUM(column_name) FROM table_name;
: Calculate the sum of the specified columns in the table.SELECT AVG(column_name) FROM table_name;
: Calculate the average of the specified column in the table.SELECT MAX(column_name) FROM table_name;
: Returns the maximum value of the specified column in the table.SELECT MIN(column_name) FROM table_name;
: Returns the minimum value of the specified column in the table.
2. String functions:
SELECT CONCAT(first_name, '-', last_name) AS full_name FROM table_name;
: Concatenatefirst_name
the andlast_name
fields into a complete name.SELECT SUBSTRING(column_name, start_position, length) FROM table_name;
: Extract a substring of specified length starting from the specified position.SELECT LENGTH(column_name) FROM table_name;
: Returns the length of the string.SELECT LOWER(column_name) FROM table_name;
:Convert the string to lowercase.SELECT UPPER(column_name) FROM table_name;
:Convert the string to uppercase.
3. Date and time functions
SELECT NOW();
: Returns the current date and time.SELECT DATE(column_name) FROM table_name;
:Extract the date part from a datetime value.SELECT TIME(column_name) FROM table_name;
: Extract the time part from a datetime value.SELECT YEAR(column_name) FROM table_name;
:Extract the year from the date.SELECT MONTH(column_name) FROM table_name;
: Extract the month from the date.
# 获取当前日期,当前时间,截取日期,截取时分秒,截取年,截取月,截取日
select curdate() ,now(),date(now()),time(now()) ,year(now()),month(now()),day(now())
DATE_FORMAT() :日期格式化
Specific use:
select DATE_FORMAT(CURDATE(), '%Y%m')
select DATE_FORMAT('2023-06-20 19:10:45', '%Y%m')
4. Numerical functions
SELECT ABS(column_name) FROM table_name;
: Returns the absolute value in the column.SELECT ROUND(column_name, decimal_places) FROM table_name;
: Rounds a value to the specified number of decimal places.SELECT CEILING(column_name) FROM table_name;
:Rounded up.SELECT FLOOR(column_name) FROM table_name;
: Round down.SELECT MOD(column_name, divisor) FROM table_name;
: Returns the remainder of the division of two numbers.
5. Conditional function
CASE
: Returns different values based on conditions.
# CASE 使用和java的 switch 类似
select name,length(name),
case
when length(name) <= 10 then '名字长度太短' #when 条件 then 输出
when length(name) >10 and length(name) <= 20 then '名字长度正常'
else '名字长度过长'
end 'name长度判定' # 列名
from user
COALESCE()
: Returns the value of the first non-empty expression.
# COALESCE 返回第一个非null的值,以此类推,如果都是null才返回null
select coalesce(null,0),coalesce(100,0)
NULLIF(A,B)
: Returns NULL if the two expressions are equal, otherwise returns the value of the first expression.
# 如果A=B则返回null,不等于则返回第一个值
select nullif('MySQL','MySQL') as 相等,
nullif('MySQL ','sqlserver ') as 不相等 from user
IF()
: Similar to Miki expression,
# IF() 满足条件则返回值1,不满足则返回值2
select if(1>0 , "张三","ZHANG"),if(1<0 , "张三","ZHANG")
2. Window function ( OVER )
Definition of OVER
OVER is used to define a window for a row. It operates on a set of values without using the GROUP BY clause to group the data. It can return both the base row's columns and the aggregated columns in the same row.
The syntax of OVER
OVER ( [ PARTITION BY column ] [ ORDER BY culumn ] )
PARTITION BY
Clauses are grouped;
ORDER BY
Clauses are sorted.
The window function OVER() specifies a set of rows, and the window function calculates the value of each row in the result set output from the window function.
The windowing function can group data without using GROUP BY, and can also return the columns of the underlying row and the aggregated columns at the same time.
Usage of OVER
The OVER windowing function must be used together with the aggregation function or sorting function, and the aggregation function generally refers to SUM(),MAX(),MIN,COUNT(),AVG()
common functions such as and so on. Sorting functions generally refer to RANK(),ROW_NUMBER(),DENSE_RANK(),NTILE()
etc.
Example of using OVER in an aggregate function
We use the SUM and COUNT functions as examples to demonstrate.
-建立测试表和测试数据
CREATE TABLE Employee
(
ID INT PRIMARY KEY,
Name VARCHAR(20),
GroupName VARCHAR(20),
Salary INT
)
INSERT INTO Employee
VALUES(1,'小明','开发部',8000), (4,'小张','开发部',7600), (5,'小白','开发部',7000), (8,'小王','财务部',5000), (9, null,'财务部',NULL), (15,'小刘','财务部',6000), (16,'小高','行政部',4500), (18,'小王','行政部',4000), (23,'小李','行政部',4500), (29,'小吴','行政部',4700);
Window function after SUM
SELECT *,
SUM(Salary) OVER(PARTITION BY Groupname) 每个组的总工资,
SUM(Salary) OVER(PARTITION BY groupname ORDER BY ID) 每个组的累计总工资,
SUM(Salary) OVER(ORDER BY ID) 累计工资,
SUM(Salary) OVER() 总工资
from Employee
The result is as follows:
Each of the windowing functions has different meanings. Let’s explain it in detail:
SUM(Salary) OVER (PARTITION BY Groupname)
Only the column Groupname after PARTITION BY is grouped, and the sum of Salary is calculated after grouping.
SUM(Salary) OVER (PARTITION BY Groupname ORDER BY ID)
Group the column Groupname after PARTITION BY, then sort by the ID after ORDER BY, and then accumulate Salary within the group.
SUM(Salary) OVER (ORDER BY ID)
Only the ID content after ORDER BY is sorted, and the sorted Salary is accumulated.
SUM(Salary) OVER ()
Summarize Salary
Window function after COUNT
SELECT *,
COUNT(*) OVER(PARTITION BY Groupname ) 每个组的个数,
COUNT(*) OVER(PARTITION BY Groupname ORDER BY ID) 每个组的累积个数,
COUNT(*) OVER(ORDER BY ID) 累积个数 ,
COUNT(*) OVER() 总个数
from Employee
The returned result is as shown below:
Each of the following window opening functions will not be interpreted one by one, but can be compared with the above window opening functions after SUM.
Example of using OVER in a sort function
We demonstrate the four sorting functions one by one
-先建立测试表和测试数据
WITH t AS
(SELECT 1 StuID,'一班' ClassName,70 Score
UNION ALL
SELECT 2,'一班',85
UNION ALL
SELECT 3,'一班',85
UNION ALL
SELECT 4,'二班',80
UNION ALL
SELECT 5,'二班',74
UNION ALL
SELECT 6,'二班',80
)
SELECT * INTO Scores FROM t;
SELECT * FROM Scores