SQL Server:PARTITION BY 和 GROUP BY 的区别

SQL Server: Difference between PARTITION BY and GROUP BY(SQL Server:PARTITION BY 和 GROUP BY 的区别)
本文介绍了SQL Server:PARTITION BY 和 GROUP BY 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多年来,我一直将 GROUP BY 用于所有类型的聚合查询.最近,我一直在对一些使用 PARTITION BY 执行聚合的代码进行逆向工程.在阅读我能找到的关于 PARTITION BY 的所有文档时,它听起来很像 GROUP BY,也许添加了一些额外的功能?它们是具有相同通用功能的两个版本,还是完全不同的东西?

I've been using GROUP BY for all types of aggregate queries over the years. Recently, I've been reverse-engineering some code that uses PARTITION BY to perform aggregations. In reading through all the documentation I can find about PARTITION BY, it sounds a lot like GROUP BY, maybe with a little extra functionality added in? Are they two versions of the same general functionality, or are they something different entirely?

推荐答案

它们用在不同的地方.group by 修改整个查询,如:

They're used in different places. group by modifies the entire query, like:

select customerId, count(*) as orderCount
from Orders
group by customerId

但是 partition by 只适用于 a窗口函数,如row_number:

But partition by just works on a window function, like row_number:

select row_number() over (partition by customerId order by orderId)
    as OrderNumberForThisCustomer
from Orders

group by 通常通过将它们汇总并计算每行的平均值或总和来减少返回的行数.partition by 不会影响返回的行数,但会改变窗口函数结果的计算方式.

A group by normally reduces the number of rows returned by rolling them up and calculating averages or sums for each row. partition by does not affect the number of rows returned, but it changes how a window function's result is calculated.

这篇关于SQL Server:PARTITION BY 和 GROUP BY 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)