本周之前,对于数据库的使用仅限于简单的增删改查(insert、delete、updata、select),而这一周由于工作需要,对一些sql函数、sql语句多表联合查询、T-SQL语句基本语法、存储过程编写等有了简单的学习,现将一周所学进行总结、归纳。
本文主要总结sql语句中的 常用sql函数和多表联合查询知识。直接通过实例进行讲解。
本文学习过程中主要参考了:http://www.w3school.com.cn/sql/sql_where.asp
设计到的表有:
表1: Orders
O_Id OrderDate OrderPrice CustomerName
1 2008/12/29 1000 Bush
2 2008/11/23 1600 Carter
3 2008/10/05 700 Bush
4 2008/09/28 1000 Bush
5 2008/08/06 2000 Adams
6 2008/07/21 100 Carter
表2:Customer
CustomerID CustomerName
1 Bush
2 Carter
3 Adams
1、利用distinct去除重复
基本语法
SELECT DISTINCT 列名称 FROM 表名称
SELECT distinct CustomerName FROM Orders --distinct 去除重复
结果:
CustomerName
Adams
Bush
Carter
2、GROUP BY 提取组合 并去重
SELECT CustomerName, OrderPrice
FROM Orders
GROUP BY CustomerName, OrderPrice
结果:
CustomerName OrderPrice
Adams 2000
Bush 700
Bush 1000
Carter 100
Carter 1600
SELECT CustomerName, OrderPrice, count(*) as 重复数
FROM Orders
GROUP BY CustomerName, OrderPrice
结果:
CustomerName OrderPrice 重复数
Adams 2000 1
Bush 700 1
Bush 1000 2
Carter 100 1
Carter 1600 1
4、COUNT(1) 和 GROUP BY
SELECT CustomerName, COUNT(1) AS 重复数
FROM Orders
GROUP BY CustomerName --记录Customer 每种值的记录数
结果:
CustomerName 重复数
Adams 1
Bush 3
Carter 2
5、sum 和 GROUP BY
SELECT CustomerName, sum(OrderPrice) AS sumOrderPrice
FROM Orders
GROUP BY CustomerName --记录Customer 每种值的对应的OrderPrice的累加和
CustomerName sumOrderPrice
Adams 2000
Bush 2700
Carter 1700
SELECT B.CustomerID, A.CustomerName, AVG(OrderPrice) AS 平均值
FROM Orders AS A,Customer AS B
GROUP BY B.CustomerID, A.CustomerName
结果: 可以看出 Groupby 将 B.CustomerID (1,2,3) 和 A.CustomerName(Adams、Bush、Carter ) 进行的全部任意组合, 但平均值依然按Orders表来求的
CustomerID CustomerName 平均值
1 Adams 2000
1 Bush 900
1 Carter 850
2 Adams 2000
2 Bush 900
2 Carter 850
3 Adams 2000
3 Bush 900
3 Carter 850
7、AVG 和 GROUP BY 的多表联合查询 加上where
SELECT B.CustomerID, A.CustomerName, AVG(OrderPrice) AS 平均值
FROM Orders AS A,Customer AS B
WHERE A.CustomerName = B.CustomerName
GROUP BY B.CustomerID, A.CustomerNme
结果:
CustomerID CustomerName 平均值
1 Bush 900
2 Carter 850
3 Adams 2000