【SQL】掌握SQL查询技巧:数据分组与排序

目录
  • [1. GROUP BY](#1. GROUP BY)
    • [1.1 定义与用途](#1.1 定义与用途)
    • [1.2 示例说明](#1.2 示例说明)
    • [1.3 注意事项](#1.3 注意事项)
    • [1.4 可视化示例](#1.4 可视化示例)
  • [2. ORDER BY](#2. ORDER BY)
    • [2.1 定义与用途](#2.1 定义与用途)
    • [2.2 升序说明(默认)](#2.2 升序说明(默认))
    • [2.3 降序排序](#2.3 降序排序)
    • [2.4 多列排序](#2.4 多列排序)
    • [2.5 可视化示例](#2.5 可视化示例)
  • [3. GROUP BY 与 ORDER BY 的结合使用](#3. GROUP BY 与 ORDER BY 的结合使用)
  • [4. 可视化示例](#4. 可视化示例)
  • 总结

在数据库管理中,SQL(结构化查询语言)是一个强大的工具,它允许用户从数据库中提取和操作数据。对数据的有效处理通常需要进行分组和排序操作。在这篇博客中,我们将深入讨论 SQL 中的 GROUP BYORDER BY 子句,帮助你更好地理解如何使用这些功能来组织和排序你的数据。

1. GROUP BY

1.1 定义与用途

GROUP BY 子句用于将来自 SELECT 查询的数据行分组,通常与聚合函数(如 COUNTSUMAVGMAXMIN)一起使用,以便对每个组执行计算。这种分组使我们能够对数据进行汇总分析,提取有用的信息。

1.2 示例说明

假设我们有一个名为 sales 的表,其中包含以下数据:

id

product

quantity

price

sale_date

1

Apple

10

1.00

2024-01-01

2

Banana

20

0.50

2024-01-02

3

Apple

15

1.00

2024-01-03

4

Banana

25

0.50

2024-01-04

5

Cherry

30

2.00

2024-01-05

现在,如果我们想要统计每种水果的总销售数量,可以使用如下 SQL 查询:

复制代码
SELECT product, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product;

解释

  • SELECT product:选择产品名称。
  • SUM(quantity) AS total_quantity:对每种产品的销售数量求和,并命名为 total_quantity
  • FROM sales:指定数据源表。
  • GROUP BY product:按 product 列对结果进行分组。

输出结果

product

total_quantity

Apple

25

Banana

45

Cherry

30

1.3 注意事项

  • 非聚合字段 :当使用 GROUP BY 时,SELECT 子句中的所有非聚合列必须在 GROUP BY 子句中列出,否则会导致错误。

    复制代码
    -- 错误示例:无法只返回 product 列而不 GROUP BY price
    SELECT product, price, SUM(quantity)
    FROM sales
    GROUP BY product; -- 会导致错误
  • NULL 值处理:在进行分组时,NULL 值会被视为同一组。

1.4 可视化示例

通过以下可视化图示,可以更直观地理解 GROUP BY 的工作原理。

#mermaid-svg-kHXD6REa28VRgscy {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-kHXD6REa28VRgscy .error-icon{fill:#552222;}#mermaid-svg-kHXD6REa28VRgscy .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-kHXD6REa28VRgscy .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-kHXD6REa28VRgscy .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-kHXD6REa28VRgscy .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-kHXD6REa28VRgscy .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-kHXD6REa28VRgscy .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-kHXD6REa28VRgscy .marker{fill:#333333;stroke:#333333;}#mermaid-svg-kHXD6REa28VRgscy .marker.cross{stroke:#333333;}#mermaid-svg-kHXD6REa28VRgscy svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-kHXD6REa28VRgscy .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-kHXD6REa28VRgscy .cluster-label text{fill:#333;}#mermaid-svg-kHXD6REa28VRgscy .cluster-label span{color:#333;}#mermaid-svg-kHXD6REa28VRgscy .label text,#mermaid-svg-kHXD6REa28VRgscy span{fill:#333;color:#333;}#mermaid-svg-kHXD6REa28VRgscy .node rect,#mermaid-svg-kHXD6REa28VRgscy .node circle,#mermaid-svg-kHXD6REa28VRgscy .node ellipse,#mermaid-svg-kHXD6REa28VRgscy .node polygon,#mermaid-svg-kHXD6REa28VRgscy .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-kHXD6REa28VRgscy .node .label{text-align:center;}#mermaid-svg-kHXD6REa28VRgscy .node.clickable{cursor:pointer;}#mermaid-svg-kHXD6REa28VRgscy .arrowheadPath{fill:#333333;}#mermaid-svg-kHXD6REa28VRgscy .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-kHXD6REa28VRgscy .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-kHXD6REa28VRgscy .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-kHXD6REa28VRgscy .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-kHXD6REa28VRgscy .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-kHXD6REa28VRgscy .cluster text{fill:#333;}#mermaid-svg-kHXD6REa28VRgscy .cluster span{color:#333;}#mermaid-svg-kHXD6REa28VRgscy div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-kHXD6REa28VRgscy :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}#mermaid-svg-kHXD6REa28VRgscy .watermark>*{fill:#fff!important;stroke:none!important;font-size:15px!important;opacity:0.8!important;}#mermaid-svg-kHXD6REa28VRgscy .watermark span{fill:#fff!important;stroke:none!important;font-size:15px!important;opacity:0.8!important;}

Group By: Product

Sum Quantities

CSDN @ 2136

Sales Table

Grouped Data

Aggregated Results

CSDN @ 2136

  • Sales Table:原始数据表,包含所有销售记录。
  • Grouped Data :通过 GROUP BY 将数据按产品分组。
  • Aggregated Results :应用聚合函数(如 SUM),计算每种产品的总销售数量。

2. ORDER BY

2.1 定义与用途

ORDER BY 子句用于对查询结果进行排序。默认情况下,排序是升序的,但可以使用 DESC 关键字指定降序排序。这有助于用户根据特定的需求查看数据。

2.2 升序说明(默认)

继续使用上述 sales 表,假设我们想按销售日期对销售记录进行排序,可以使用如下 SQL 查询:

复制代码
SELECT *
FROM sales
ORDER BY sale_date ASC;

解释

  • SELECT *:选择所有列。
  • FROM sales:指定数据源表。
  • ORDER BY sale_date ASC:按 sale_date 列升序排序。

输出结果

id

product

quantity

price

sale_date

1

Apple

10

1.00

2024-01-01

2

Banana

20

0.50

2024-01-02

3

Apple

15

1.00

2024-01-03

4

Banana

25

0.50

2024-01-04

5

Cherry

30

2.00

2024-01-05

2.3 降序排序

如果想按销售数量降序排序,可以使用:

复制代码
SELECT *
FROM sales
ORDER BY quantity DESC;

解释

  • ORDER BY quantity DESC:按 quantity 列降序排序。

输出结果

id

product

quantity

price

sale_date

5

Cherry

30

2.00

2024-01-05

4

Banana

25

0.50

2024-01-04

3

Apple

15

1.00

2024-01-03

2

Banana

20

0.50

2024-01-02

1

Apple

10

1.00

2024-01-01

2.4 多列排序

你可以使用多个列进行排序。例如,首先按产品名称升序,然后按销售数量降序:

复制代码
SELECT *
FROM sales
ORDER BY product ASC, quantity DESC;

解释

  • ORDER BY product ASC, quantity DESC:按 product 列升序,若有相同的产品再按 quantity 降序排序。

输出结果示例

id

product

quantity

price

sale_date

1

Apple

10

1.00

2024-01-01

3

Apple

15

1.00

2024-01-03

2

Banana

20

0.50

2024-01-02

4

Banana

25

0.50

2024-01-04

5

Cherry

30

2.00

2024-01-05

2.5 可视化示例

通过以下可视化图示,可以更直观地理解 ORDER BY 的工作原理。

#mermaid-svg-2JukF3Z6iaQynXho {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-2JukF3Z6iaQynXho .error-icon{fill:#552222;}#mermaid-svg-2JukF3Z6iaQynXho .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-2JukF3Z6iaQynXho .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-2JukF3Z6iaQynXho .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-2JukF3Z6iaQynXho .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-2JukF3Z6iaQynXho .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-2JukF3Z6iaQynXho .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-2JukF3Z6iaQynXho .marker{fill:#333333;stroke:#333333;}#mermaid-svg-2JukF3Z6iaQynXho .marker.cross{stroke:#333333;}#mermaid-svg-2JukF3Z6iaQynXho svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-2JukF3Z6iaQynXho .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-2JukF3Z6iaQynXho .cluster-label text{fill:#333;}#mermaid-svg-2JukF3Z6iaQynXho .cluster-label span{color:#333;}#mermaid-svg-2JukF3Z6iaQynXho .label text,#mermaid-svg-2JukF3Z6iaQynXho span{fill:#333;color:#333;}#mermaid-svg-2JukF3Z6iaQynXho .node rect,#mermaid-svg-2JukF3Z6iaQynXho .node circle,#mermaid-svg-2JukF3Z6iaQynXho .node ellipse,#mermaid-svg-2JukF3Z6iaQynXho .node polygon,#mermaid-svg-2JukF3Z6iaQynXho .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-2JukF3Z6iaQynXho .node .label{text-align:center;}#mermaid-svg-2JukF3Z6iaQynXho .node.clickable{cursor:pointer;}#mermaid-svg-2JukF3Z6iaQynXho .arrowheadPath{fill:#333333;}#mermaid-svg-2JukF3Z6iaQynXho .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-2JukF3Z6iaQynXho .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-2JukF3Z6iaQynXho .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-2JukF3Z6iaQynXho .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-2JukF3Z6iaQynXho .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-2JukF3Z6iaQynXho .cluster text{fill:#333;}#mermaid-svg-2JukF3Z6iaQynXho .cluster span{color:#333;}#mermaid-svg-2JukF3Z6iaQynXho div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-2JukF3Z6iaQynXho :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}#mermaid-svg-2JukF3Z6iaQynXho .watermark>*{fill:#fff!important;stroke:none!important;font-size:15px!important;opacity:0.8!important;}#mermaid-svg-2JukF3Z6iaQynXho .watermark span{fill:#fff!important;stroke:none!important;font-size:15px!important;opacity:0.8!important;}

Order By: Sale Date

CSDN @ 2136

Sales Table

Sorted Data

CSDN @ 2136

  • Sales Table:原始数据表,包含所有销售记录。
  • Sorted Data :通过 ORDER BY 对数据进行排序,得到有序的销售记录。

3. GROUP BY 与 ORDER BY 的结合使用

我们可以将 GROUP BYORDER BY 结合起来,首先对数据进行分组,然后对结果进行排序。例如,统计每种水果的总销售数量,并按数量降序排列:

复制代码
SELECT product, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product
ORDER BY total_quantity DESC;

解释

  • SUM(quantity) 计算每种水果的销售总量。
  • ORDER BY total_quantity DESC 将结果按总销售数量降序排序。

输出结果

product

total_quantity

Banana

45

Cherry

30

Apple

25

4. 可视化示例

通过以下可视化图示,可以更直观地理解 GROUP BYORDER BY 的工作原理。这里使用 Mermaid 图形描述工具来展示数据流向和处理过程。

#mermaid-svg-aFPJv5TLetPW4EGJ {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-aFPJv5TLetPW4EGJ .error-icon{fill:#552222;}#mermaid-svg-aFPJv5TLetPW4EGJ .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-aFPJv5TLetPW4EGJ .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-aFPJv5TLetPW4EGJ .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-aFPJv5TLetPW4EGJ .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-aFPJv5TLetPW4EGJ .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-aFPJv5TLetPW4EGJ .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-aFPJv5TLetPW4EGJ .marker{fill:#333333;stroke:#333333;}#mermaid-svg-aFPJv5TLetPW4EGJ .marker.cross{stroke:#333333;}#mermaid-svg-aFPJv5TLetPW4EGJ svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-aFPJv5TLetPW4EGJ .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-aFPJv5TLetPW4EGJ .cluster-label text{fill:#333;}#mermaid-svg-aFPJv5TLetPW4EGJ .cluster-label span{color:#333;}#mermaid-svg-aFPJv5TLetPW4EGJ .label text,#mermaid-svg-aFPJv5TLetPW4EGJ span{fill:#333;color:#333;}#mermaid-svg-aFPJv5TLetPW4EGJ .node rect,#mermaid-svg-aFPJv5TLetPW4EGJ .node circle,#mermaid-svg-aFPJv5TLetPW4EGJ .node ellipse,#mermaid-svg-aFPJv5TLetPW4EGJ .node polygon,#mermaid-svg-aFPJv5TLetPW4EGJ .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-aFPJv5TLetPW4EGJ .node .label{text-align:center;}#mermaid-svg-aFPJv5TLetPW4EGJ .node.clickable{cursor:pointer;}#mermaid-svg-aFPJv5TLetPW4EGJ .arrowheadPath{fill:#333333;}#mermaid-svg-aFPJv5TLetPW4EGJ .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-aFPJv5TLetPW4EGJ .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-aFPJv5TLetPW4EGJ .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-aFPJv5TLetPW4EGJ .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-aFPJv5TLetPW4EGJ .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-aFPJv5TLetPW4EGJ .cluster text{fill:#333;}#mermaid-svg-aFPJv5TLetPW4EGJ .cluster span{color:#333;}#mermaid-svg-aFPJv5TLetPW4EGJ div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-aFPJv5TLetPW4EGJ :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}#mermaid-svg-aFPJv5TLetPW4EGJ .watermark>*{fill:#fff!important;stroke:none!important;font-size:15px!important;opacity:0.8!important;}#mermaid-svg-aFPJv5TLetPW4EGJ .watermark span{fill:#fff!important;stroke:none!important;font-size:15px!important;opacity:0.8!important;}

Group By: Product

Sum Quantities

Order By: Total Quantity Desc

CSDN @ 2136

Sales Table

Grouped Data

Aggregated Results

Final Sorted Results

CSDN @ 2136

图示解读

  • Sales Table:原始数据表,包含所有销售记录。
  • Grouped Data :通过 GROUP BY 将数据按产品分组。
  • Aggregated Results :应用聚合函数(如 SUM),计算每种产品的总销售数量。
  • Final Sorted Results :通过 ORDER BY 对聚合后的结果进行排序,最终得到按销售数量排序的结果。

总结

通过掌握 GROUP BYORDER BY 子句,你可以有效地分析和整理 SQL 查询的结果。无论是进行数据汇总还是结果排序,这两者都是数据分析中不可或缺的工具。理解它们的用法可以帮助你更快速、高效地处理和分析数据。

希望本文能帮助你更好地理解和应用 SQL 查询技巧!如有任何问题或需要进一步的示例,请随时留言!


相关推荐
霸道流氓气质2 分钟前
ApiPost 中配置自动获取 Token 并调用业务接口完整指南
java·服务器·数据库
独隅23 分钟前
IntelliJ IDEA 接入多种AI大模型插件终极指南(2026.1 企业合规版)
java·人工智能·intellij-idea
还是奇怪1 小时前
Simon Willison 用 DSPy 优化 Datasette Agent 提示词:提示工程正在变成可测试的软件工程
java·开发语言·软件工程
zfoo-framework1 小时前
1.ansible安装 2.虚拟机克隆
java
码上解惑1 小时前
从 Dify 工作流说起:常用节点怎么选、怎样组合?
java·人工智能·ai·agent·dify·智能体·spring ai
青山木2 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
程序员-珍2 小时前
报错下载android sdk失败
android·java
糖果店的幽灵3 小时前
langgraph分支之 - 动态分支(Dynamic Branch)
java·前端·javascript·人工智能·langgraph
吃饱了得干活3 小时前
亿级订单表分库分表设计,从0到1全流程
java·数据库·面试
唐青枫3 小时前
Java Spring Security 实战详解:从登录认证到 JWT 权限控制
java