sql的sum函数(与group by,having子句混合使用)

 

SELECT Customer,SUM(OrderPrice) FROM Orders

WHERE Customer='Bush' OR Customer='Adams'

GROUP BY Customer

HAVING SUM(OrderPrice)>1500

 

Select sum(downloads) as download from factdownloads_new

where date_time='2013-12-11' and storename='anzhi'

结果:3595443702                 3253205502              3631413902              3342157901

 

 用别名as:

Select sum(downloads) from factdownloads_new

where date_time='2013-12-11' and storename='hiapk'

结果:8937649006            8927173006              8952359006     8978768006

 

sum函数

引自:http://www.w3school.com.cn/sql/sql_groupby.asp

SQL GROUP BY 实例

我们拥有下面这个 "Orders" 表:

O_Id OrderDate OrderPrice Customer
1 2008/12/29 1000 Bush
2 2008/11/23 1600 Carter
3 2008/10/05 700 Bush
4 2008/09/28 300 Bush
5 2008/08/06 2000 Adams
6 2008/07/21 100 Carter

现在,我们希望查找每个客户的总金额(总订单)。

我们想要使用 GROUP BY 语句对客户进行组合。

我们使用下列 SQL 语句:

SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer

结果集类似这样:

Customer SUM(OrderPrice)
Bush 2000
Carter 1700
Adams 2000

 

sum与having一起使用

过滤数据结果:HAVING 子句筛选满足条件的结果集

在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与合计函数一起使用

这个 "Orders" 表:

O_Id OrderDate OrderPrice Customer
1 2008/12/29 1000 Bush
2 2008/11/23 1600 Carter
3 2008/10/05 700 Bush
4 2008/09/28 300 Bush
5 2008/08/06 2000 Adams
6 2008/07/21 100 Carter

现在,我们希望查找订单总金额少于 2000 的客户。

我们使用如下 SQL 语句:

SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000

结果集类似:

Customer SUM(OrderPrice)
Carter 1700

现在我们希望查找客户 "Bush" 或 "Adams" 拥有超过 1500 的订单总金额。

我们在 SQL 语句中增加了一个普通的 WHERE 子句:

SELECT Customer,SUM(OrderPrice) FROM Orders
WHERE Customer='Bush' OR Customer='Adams'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500

结果集:

Customer SUM(OrderPrice)
Bush 2000
Adams 2000

更多 0

你可能感兴趣的:(sql,mysql)