当前位置: 首页 > 图文教程 > 数据库 > MSSQL > SQLServer2005 中的几个统计技巧

MSSQL
SQL Server数据库技术(82)
SQL Server数据库技术(83)
SQL Server数据库技术(84)
SQL Server数据库技术(85)
SQL Server数据库技术(86)
SQL Server数据库技术(87)
SQL Server数据库技术(88)
SQL Server数据库技术(89)
SQL Server数据库技术(90)
SQL Server数据库技术(91)
SQL Server数据库技术(92)
SQL Server数据库技术(93)
SQL Server数据库技术(94)
SQL Server数据库技术(95)
SQL Server数据库技术(96)
SQL Server数据库技术(97)
SQL Server数据库技术(98)
SQL Server数据库技术(99)
SQL Server数据库技术(100)
SQL Server数据库技术(101)

MSSQL 中的 SQLServer2005 中的几个统计技巧


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 193 ::
收藏到网摘: n/a

先看下面的一个表格,我们从左边的两列信息来统计出右边的结果。
在SQLServer中我们可以用over子句中来代替子查询实现来提高效率,over子句除了排名函数之外也可以和聚合函数配合。实现代码如下:
复制代码 代码如下:

use tempdb
go
if (object_id ('tb' ) is not null )
drop table tb
go
create table tb (name varchar (10 ), val int )
go
insert into tb
select 'aa' , 10
union all select 'aa' , 20
union all select 'aa' , 20
union all select 'aa' , 30
union all select 'bb' , 55
union all select 'bb' , 45
union all select 'bb' , 0
select *
, 排名 = rank ()over (partition by name order by val )
, 占比 = cast (val * 1.0 / sum (val )over (partition by name ) as decimal (2 , 2 ))
, 距最大 = val - max (val )over (partition by name )
, 距最小 = val - min (val )over (partition by name )
, 距平均 = val - avg (val )over (partition by name )
from tb