0、创建示例表并插入数据:
CREATE TABLE orders ( order_id INT PRIMARY KEY AUTO_INCREMENT , customer_name VARCHAR ( 50 ) NOT NULL , order_date DATE , total_amount DECIMAL ( 10 , 2 )
) ; INSERT INTO orders ( customer_name, order_date, total_amount) VALUES ( 'lfsun-1' , '2023-07-15' , 120.50 ) , ( 'lfsun-2' , '2023-07-16' , 85.20 ) , ( 'lfsun-4' , '2023-07-17' , 320.75 ) , ( 'lfsun-5' , '2023-07-18' , 210.00 ) , ( 'lfsun-6' , '2023-07-19' , 450.60 ) ;
1、使用COUNT计算订单数量:
SELECT COUNT ( * ) AS order_count FROM orders;
2、使用SUM计算总金额:
SELECT SUM ( total_amount) AS total_amount FROM orders;
3、使用AVG计算平均金额:
SELECT AVG ( total_amount) AS average_amount FROM orders;
4、使用MAX和MIN查找最大和最小金额:
SELECT MAX ( total_amount) AS max_amount, MIN ( total_amount) AS min_amount FROM orders;
5、使用CONCAT连接字符串:
SELECT CONCAT( 'Order #' , order_id, ' - ' , customer_name) AS order_info FROM orders;
6、使用SUBSTRING截取字符串:
SELECT SUBSTRING( order_id, - 3 ) AS last_three_digits FROM orders;
7、使用REPLACE替换字符串:
SELECT REPLACE ( customer_name, '1' , '11' ) AS modified_name FROM orders;
8、使用ROUND对数字进行四舍五入:
SELECT ROUND ( total_amount, 2 ) AS rounded_amount FROM orders;
9、使用TRIM去除字符串两侧的空格:
SELECT TRIM( customer_name) AS trimmed_name FROM orders;
10、使用DATE_FORMAT格式化日期:
SELECT DATE_FORMAT( order_date, '%Y-%m-%d' ) AS formatted_date FROM orders;
11、使用NOW获取当前日期和时间:
SELECT NOW ( ) AS current_datetime FROM orders;
12、使用RAND生成随机数:
SELECT RAND( ) AS random_number FROM orders;
13、使用IF条件判断:
SELECT customer_name, IF ( total_amount >= 300 , 'High Value' , 'Low Value' ) AS value_category FROM orders;
14、使用CASE条件表达式:
SELECT customer_name, total_amount, CASE WHEN total_amount >= 400 THEN 'High Value' WHEN total_amount >= 200 THEN 'Medium Value' ELSE 'Low Value' END AS value_category
FROM orders;
15、使用CAST和CONVERT进行数据类型转换:
SELECT customer_name, CAST( total_amount AS SIGNED) AS total_amount_integer
FROM orders;