合计函数 (比如 SUM) 常常需要添加 GROUP BY 功能。
GROUP BY...
把 GROUP BY 加入 SQL 的原因是,合计函数(比如 SUM)在每次被调用后会返回所有列的合计,如果没有 GROUP BY,就无法计算每个单独列值组合的总和。
GROUP BY 的语法:
SELECT column,SUM(column) FROM table GROUP BY
column
GROUP BY 实例
表 "Sales":
Company | Amount |
---|---|
W3School | 6500 |
IBM | 5500 |
W3School | 7300 |
SQL:
SELECT Company, SUM(Amount) FROM Sales
结果:
Company | SUM(Amount) |
---|---|
W3School | 19300 |
IBM | 19300 |
W3School | 19300 |
上面的代码是无效的,这是由于被返回的列没有进行部分合计。GROUP BY 子句能解决这个问题:
SELECT Company,SUM(Amount) FROM Sales GROUP BY Company
结果:
Company | SUM(Amount) |
---|---|
W3School | 13800 |
IBM | 5500 |
HAVING...
把 HAVING 加入 SQL 的原因是,WHERE 无法应用于合计函数,而如果没有 HAVING,就无法测试结果条件。
HAVING 的语法:
SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column) condition value
表 "Sales":
Company | Amount |
---|---|
W3School | 6500 |
IBM | 5500 |
W3School | 7300 |
SQL:
SELECT Company,SUM(Amount) FROM Sales GROUP BY Company HAVING SUM(Amount)>10000
结果:
Company | SUM(Amount) |
---|---|
W3School | 13800 |