SqlServer窗口函数
发布时间:2020-12-12 13:24:03 所属栏目:MsSql教程 来源:网络整理
导读:窗口函数的作用 窗口函数是对一组值进行操作,不需要使用group by子句对数据进行分组,还能够在同一行中同时返回基础行的列和聚合列。窗口函数,基础列和聚合列的查询都非常简单。 语法格式 窗口函数的语法格式如下: over([partition by value_expression,
窗口函数的作用窗口函数是对一组值进行操作,不需要使用group by子句对数据进行分组,还能够在同一行中同时返回基础行的列和聚合列。窗口函数,基础列和聚合列的查询都非常简单。 语法格式窗口函数的语法格式如下: over([partition by value_expression,...,[n]],<order by by_value>)
首先创建一张测试表: CREATE TABLE [dbo].[Scores]( [Id] [int] IDENTITY(1,1) NOT NULL,[StudentId] [int] NULL,[CSharp] [float] NULL,[SqlServer] [float] NULL,[C语言] [float] NULL )
表中数据如下: 应用实例1、avg()求平均值: /*用group by分组 */
SELECT StudentId,CSharp,AVG(CSharp) AS '平均分' FROM Scores group by StudentId,CSharp
/*用over()分组,group by可省略 *partition by studentid,CSharp 表示按studentid,CSharp分组 */
SELECT StudentId,AVG(csharp) over(partition by studentid,CSharp) AS '平均分' from Scores
/*用over()分组,group by可省略 *默认情况下所有数据为同一分组 */
SELECT StudentId,AVG(CSharp) over() AS '平均分' FROM Scores
/*用over()分组,group by可省略 *partition by StudentId表示按StudentId分组 */
SELECT StudentId,AVG(CSharp) over(partition by StudentId) AS '平均分' FROM Scores
2、cast()转换数据格式 /*用group by分组 *将avg(CSharp)转换为decimal(5,2)格式 */
select StudentId,cast(AVG(csharp) as decimal(5,2)) as'平均分' from Scores group by StudentId,CSharp
/*用over()分组,group by可省略 *partition by studentid,CSharp表示按studentid,CSharp分组 *将avg(CSharp)转换为decimal(5,cast(AVG(csharp) over(partition by studentid,CSharp) as decimal(5,2)) as'平均分' from Scores
/*用over()分组,group by可省略 *默认情况下所有数据为同一分组 *将avg(CSharp)转换为decimal(5,cast(AVG(csharp) over() as decimal(5,2)) as'平均分' from Scores
/*用over()分组,group by可省略 *partition by studentid表示按studentid分组 *将avg(CSharp)转换为decimal(5,cast(AVG(csharp) over(partition by studentid) as decimal(5,2)) as'平均分' from Scores
3、row_number()创建列编号 select row_number() over(partition by StudentId order by CSharp asc) as rowNumber,StudentId,CSharp from Scores
4、rank()排序 select rank() over(partition by StudentId order by CSharp),CSharp from dbo.Scores
select rank() over(order by CSharp),CSharp from dbo.Scores
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |