简体   繁体   English

我如何使用 T-SQL Group By

[英]How do I use T-SQL Group By

I know I need to have (although I don't know why) a GROUP BY clause on the end of a SQL query that uses any aggregate functions like count , sum , avg , etc:我知道我需要(虽然我不知道为什么)在使用任何聚合函数(如countsumavg等)的 SQL 查询末尾有一个GROUP BY子句:

SELECT count(userID), userName
FROM users
GROUP BY userName

When else would GROUP BY be useful, and what are the performance ramifications?还有什么时候GROUP BY有用,性能影响是什么?

To retrieve the number of widgets from each widget category that has more than 5 widgets, you could do this:要从具有 5 个以上小部件的每个小部件类别中检索小部件的数量,您可以执行以下操作:

SELECT WidgetCategory, count(*)
FROM Widgets
GROUP BY WidgetCategory
HAVING count(*) > 5

The "having" clause is something people often forget about, instead opting to retrieve all their data to the client and iterating through it there. “拥有”子句是人们经常忘记的东西,而是选择将所有数据检索到客户端并在那里迭代。

GROUP BY is similar to DISTINCT in that it groups multiple records into one. GROUP BY 类似于​​ DISTINCT,因为它将多条记录归为一个。

This example, borrowed from http://www.devguru.com/technologies/t-sql/7080.asp , lists distinct products in the Products table.这个例子是从http://www.devguru.com/technologies/t-sql/7080.asp借来的,它在 Products 表中列出了不同的产品。

SELECT Product FROM Products GROUP BY Product

Product
-------------
Desktop
Laptop
Mouse
Network Card
Hard Drive
Software
Book
Accessory

The advantage of GROUP BY over DISTINCT, is that it can give you granular control when used with a HAVING clause. GROUP BY 相对于 DISTINCT 的优势在于,当与 HAVING 子句一起使用时,它可以为您提供精细控制。

SELECT Product, count(Product) as ProdCnt
FROM Products
GROUP BY Product
HAVING count(Product) > 2

Product      ProdCnt
--------------------
Desktop          10
Laptop            5
Mouse             3
Network Card      9
Software          6

Group By forces the entire set to be populated before records are returned (since it is an implicit sort). Group By 强制在返回记录之前填充整个集合(因为它是一种隐式排序)。

For that reason (and many others), never use a Group By in a subquery.出于这个原因(以及许多其他原因),永远不要在子查询中使用 Group By。

Counting the number of times tags are used might be a google example:计算使用标签的次数可能是一个谷歌示例:

SELECT TagName, Count(*)
AS TimesUsed
FROM Tags
GROUP BY TagName ORDER TimesUsed

If you simply want a distinct value of tags, I would prefer to use the DISTINCT statement.如果你只是想要一个不同的标签值,我更喜欢使用DISTINCT语句。

SELECT DISTINCT TagName
FROM Tags
ORDER BY TagName ASC

GROUP BY also helps when you want to generate a report that will average or sum a bunch of data.当您想要生成对一堆数据进行平均或求和的报告时,GROUP BY 也很有帮助。 You can GROUP By the Department ID and the SUM all the sales revenue or AVG the count of sales for each month.您可以按部门 ID 和 SUM 对所有销售收入进行 GROUP 或 AVG 每个月的销售计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM