MySQL 知识点复习- 6. ORDER BY, GROUP BY

ORDER BY

ORDER BY 可以按照一个或多个列的值进行升序(ASC)或者降序(DESC)排序。

SELECT column1, column2, ...

FROM table_name

ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;

例子:

sql 复制代码
SELECT  * FROM products

ORDER BY product_name ASC;

以上 SQL 语句将选择产品表 products 中的所有产品,并按产品名称升序 ASC 排序。

GROUP BY

  • GROUP BY 语句根据一个或多个列对结果集进行分组。
  • 在分组的列上我们可以使用 COUNT, SUM, AVG,等函数。
sql 复制代码
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1;

假设有一个名为 orders 的表,包含以下列:order_id、customer_id、order_date 和 order_amount

我们想要按照 customer_id 进行分组,并计算每个客户的订单总金额,SQL 语句如下:

sql 复制代码
SELECT customer_id, SUM(order_amount) AS total_amount

FROM orders

GROUP BY customer_id;

在SQL中使用GROUP BY子句可以根据一个或多个列对结果进行分组。

假设我们有一个表sales,包含以下数据:假设我们有一个表sales,包含以下数据:

| product_id | store_id | sales_quantity |

| 1 | 1 | 10 |

| 1 | 1 | 15 |

| 1 | 2 | 5 |

| 2 | 1 | 20 |

| 2 | 2 | 25 |

sql 复制代码
SELECT product_id, store_id, SUM(sales_quantity) AS total_sales
FROM sales
GROUP BY product_id, store_id;

根据product_idstore_id组合进行分组,该查询结果将是:

| product_id | store_id | total_sales |

| 1 | 1 | 25 |

| 1 | 2 | 5 |

| 2 | 1 | 20 |

| 2 | 2 | 25 |

相关推荐
于眠牧北2 天前
MySQL的锁类型,表锁,行锁,MVCC中所使用的临键锁
mysql
Turnip12024 天前
深度解析:为什么简单的数据库"写操作"会在 MySQL 中卡住?
后端·mysql
加号34 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏4 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
WeiXin_DZbishe4 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
爱可生开源社区4 天前
MySQL 性能优化:真正重要的变量
数据库·mysql
小马爱打代码5 天前
MySQL性能优化核心:InnoDB Buffer Pool 详解
数据库·mysql·性能优化
风流 少年5 天前
mysql mcp
数据库·mysql·adb
西门吹雪分身5 天前
mysql之数据离线迁移
数据库·mysql
轩情吖5 天前
MySQL初识
android·数据库·sql·mysql·adb·存储引擎