SQL GROUP BY 字段在所有情况下都是可交换的吗?
在简单的查询中,GROUP BY 字段的顺序对最终结果没有影响(忽略开发人员的易读性)。
EG:SELECT COUNT(*) FROM People GROUP BY Age, Gender
将产生与翻转 GROUP BY 字段相同的结果。
一般来说,在什么条件下 GROUP BY 字段的这种明显的交换性质会失效?
我正在这里寻找一般规则(例如:“任何包含依赖于分组字段之一的子表达式的表达式”)
我很难想出一个示例来说明排序的重要性 - 但我的直觉告诉我在某些情况下确实如此。
In a simple query the order of your GROUP BY fields makes no difference (ignoring developer legibility) to the final result.
EG: SELECT COUNT(*) FROM People GROUP BY Age, Gender
will produce the same results as if the GROUP BY fields were flip-flopped.
Generally speaking, under what condition(s) does this apparent commutative property of the GROUP BY fields break down?
I'm looking for a general rule here (EG: "Any expression containing sub-expressions which depend upon one of the grouped fields")
I'm having a hard time coming up with an example of where the ordering would matter - but my gut tells me it does in some situation(s).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为唯一重要的是使用 ROLLUP 创建小计
http://msdn.microsoft.com/en-us/library/ms189305(v=sql.90).aspx
查询 1
2 的结果
1
3
6
1
2
3
6
12
(受影响的 9 行)
查询 2 的结果
2
1
3
1
2
3
3
3
6
12
(受影响的 10 行)
I think the only time it matters is when using ROLLUP to create subtotals
http://msdn.microsoft.com/en-us/library/ms189305(v=sql.90).aspx
Results from Query 1
2
1
3
6
1
2
3
6
12
(9 row(s) affected)
Results from Query 2
2
1
3
1
2
3
3
3
6
12
(10 row(s) affected)
我只是在这里推测,但如果有人实现基于 CLR 的聚合函数,顺序可能会很重要。我之前在 C# 中实现了一个聚合函数,我有这样的感觉,根据聚合实际执行的操作,分组的顺序可能会影响它。
我对聚合 CLR 函数如何与引擎交互了解不够,无法真正说出更多内容:/
I am only speculating here, but it might be possible that if someone implements CLR based aggregate functions, that the order would matter. I've implemented a aggregate function before in C# and I have this feeling that depending on what the aggregation is actually doing, that there may be a chance that the order of the group by may effect it.
I don't know enough about how aggregate CLR functions interact with the engine to really say anything more than that :/
我喜欢你的问题:)
我认为在你提到的情况下,你正在做计数(这纯粹是加法),分组的顺序并不重要。加法是可交换的,GROUP BY 不应从集合中删除任何行,它只是聚合它们以供显示。因此,将它们分组的顺序应该没有任何区别。
I like your question :)
I think in the case you mention, where you are doing counts (which is purely additive), the order of grouping doesn't matter. Addition is commutative and GROUP BY should not remove any rows from the set, it just aggregates them for display. Therefore, it shouldn't make any difference what order you group them in.
新的!!!
所以......在使用分组集时,顺序可能很重要;我必须做一些测试。
---旧的订单<>团体。
给定:
结果:
vs:
不同的 order by 显示不同的排序;但也许问题不在于顺序,而在于子集:同样,顺序在不同的子集中很重要:
NEW!!!
So... it's possible in the use of grouping sets, order may matter; i'd have to do some testing.
---OLD yeah ORDER <> Group.
Given:
RESULT:
vs:
the different order by's show a different sort; but maybe the question is not about the order but the subset: and again yes order matters in different subsets: