SQL_聚合函数使用总结

SQL__聚合函数使用总结

1.聚合函数( 均可以和distinct(去重)以及 all(全部)搭配使用 )

  • 热身

    	use AdventureWorks
    

2.Avg()

  • 例子如下
    
    	select 'Average Rate'=AVG(Rate)
    	from HumanResources.EmployeePayHistory
    	----'Average Rate' 为自己取的别名
    
    	select AVG(Rate) as Average_Rate,EmployeeID
    	from HumanResources.EmployeePayHistory
    	----as在这里的意思是“重命名”
        ----仅且在聚合函数里才能把as当作“重命名”的意思。
        
    

3.Count()

  • 例子如下

    
    	select 'Unique Rate'=COUNT (distinct Rate)
    	from HumanResources.EmployeePayHistory 
    	----'unique Rate' 为自己取的别名
    	
    	select Count(distinct Rate) as UniqueRate
    	from Humanresources.EmployeePayHistory
    	-----当所取的别名中间含有空格时,不允许用“as”这种方法来另起别名。
    	
    

4.补充

  • 聚合函数返回的只是一个唯一确定的值 如果一个查询中既有聚合函数,又要显示其他大量的数据,那一定行不通,除非包含Group by字句


  • 例子如下

    
    	select AVG(Rate) as Average_Rate,EmployeeID
    	from HumanResources.EmployeePayHistory
    	---(虽然语法上没有什么错误,但运行后你会发生error)
    	----选择列表中的列 'HumanResources.EmployeePayHistory.EmployeeID' 无效,
    	----因为该列没有包含在聚合函数或 GROUP BY 子句中
    	
    	-----可以修改为:
    	select AVG(Rate) as Average_Rate,EmployeeID
    	from HumanResources.EmployeePayHistory
    	Group by EmployeeID
    	Order by Average_Rate desc
    	
    

5.其余的聚合函数均同理

  • Min()
  • Max()
  • Sum()
发布了56 篇原创文章 · 获赞 51 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43495629/article/details/104212197