简体   繁体   English

当我们在SQL查询中使用“ group by 1”时,这是什么意思

[英]what does it mean when we use “ group by 1” in an SQL Query

I have come across a query where it is specified by 我遇到了一个查询,该查询由

select concat(21*floor(diff/21), '-', 21*floor(diff/21) + 20) as `range`,     count(*) as 
`number of users` from new_table group by 1 order by diff;

here what exactly does group by 1 mean? 这里group by 1是什么意思?

Assuming you have a Select: 假设您有一个选择:

SELECT name FROM employee GROUP BY 1;

No matter what, it will always group by the first column given in the select. 无论如何,它将始终按select中给定的第一列分组。 In this case, the column 'name' is grouped. 在这种情况下,列“名称”被分组。

So if we alternate the above statement to: 因此,如果我们将上述声明替换为:

SELECT department FROM employee GROUP BY 1;

We now group the department, without having to change the '1' in the group by. 现在,我们将部门分组,而不必在分组依据中更改“ 1”。

EDIT: (as requested by Stewart) 编辑:(按斯图尔特的要求)

If we have the following Data in table 'employe': 如果我们在“雇员”表中有以下数据:

-- name --
Walt
Walt
Brian
Barney

A simple select would deliver all rows above, whereas the 'group by 1' would result in one Walt-row: 一个简单的选择将交付上面的所有行,而“ group by 1”将导致一个Walt行:

output with group by: 与group by一起输出:

-- name --
Walt
Brian
Barney

+1 to @FabianBigler for answering first, but I'll add this: +1到@FabianBigler首先回答,但我将其添加为:

http://dev.mysql.com/doc/refman/5.6/en/select.html says: http://dev.mysql.com/doc/refman/5.6/en/select.html说:

Columns selected for output can be referred to in ORDER BY and GROUP BY clauses using column names, column aliases, or column positions. 可以在ORDER BY和GROUP BY子句中使用列名,列别名或列位置引用选择用于输出的列。 Column positions are integers and begin with 1. 列位置是整数,以1开头。

For what it's worth, this is non-standard SQL, so don't expect it to work on other brands of SQL database. 值得一提的是,这是非标准的SQL,因此不要期望它可以在其他品牌的SQL数据库上使用。

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

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