group by 子句將數(shù)據(jù)集按指定列分組并聚合每個(gè)組的指定值,語法:select aggregate_function(column_name) from table_name group by column_name。其用法包括:1. 聚合數(shù)據(jù)(計(jì)算每個(gè)組的總和、平均值等);2. 分組數(shù)據(jù)(將數(shù)據(jù)按指定列劃分為組);3. 過濾數(shù)據(jù)(結(jié)合 having 子句)。
GROUP BY 語法
GROUP BY
子句將數(shù)據(jù)集按指定列進(jìn)行分組,并聚合每個(gè)組的指定值。其語法如下:
<code>SELECT aggregate_function(column_name) FROM table_name GROUP BY column_name</code>
登錄后復(fù)制
其中:
aggregate_function
:聚合函數(shù),如 SUM()
, COUNT()
, AVG()
, MAX()
, MIN()
等。
column_name
:用于分組的列。
用法
GROUP BY
的主要用法包括:
聚合數(shù)據(jù):計(jì)算每個(gè)組的聚合值(總和、平均值、最大值、最小值等)。
分組數(shù)據(jù):將數(shù)據(jù)按指定列劃分為組,以便對每個(gè)組的數(shù)據(jù)進(jìn)行分析。
過濾數(shù)據(jù):結(jié)合 HAVING
子句,對分組后的數(shù)據(jù)進(jìn)行過濾。
示例
假設(shè)我們有一個(gè)名為 Sales
的表,包含以下數(shù)據(jù):
OrderID | Product | Category | Price |
---|---|---|---|
1 | Product A | Category 1 | 10 |
2 | Product A | Category 1 | 15 |
3 | Product B | Category 2 | 20 |
4 | Product C | Category 3 | 30 |
示例 1:計(jì)算每個(gè)類別產(chǎn)品的總價(jià)
<code class="sql">SELECT Category, SUM(Price) AS TotalPrice FROM Sales GROUP BY Category;</code>
登錄后復(fù)制
結(jié)果:
Category | TotalPrice |
---|---|
Category 1 | 25 |
Category 2 | 20 |
Category 3 | 30 |
示例 2:按產(chǎn)品分組,統(tǒng)計(jì)訂單數(shù)
<code class="sql">SELECT Product, COUNT(*) AS OrderCount FROM Sales GROUP BY Product;</code>
登錄后復(fù)制
結(jié)果:
Product | OrderCount |
---|---|
Product A | 2 |
Product B | 1 |
Product C | 1 |