Appreciated group by group by and aggregation functions and aggregate functions

group by and aggregate functions

Why can not select * from Table group by id, Why must not be *

But a function of a polymerization column or a column,

group by more than one field can be a good understanding of how to do?

Text start =========== =========

  First look at Table 1, Table named test:

 

Table 1

  Execute the following SQL statement:

1

2

SELECT name FROM test

GROUP BY name

  Operating results in Table 2:

 

Table 2

  But for a better understanding of "group by" multiple columns "and" aggregate function ", the procedure in Table 1 to Table 2, adding a fictitious intermediate table: Table 3. Here virtual talk about how to think the implementation of the above SQL statement:

1.FROM test: After the execution of the sentence, and should result in Table 1, as is the original table.

2.FROM test Group BY name: After the execution of the sentence, we can imagine generating the virtual table 3, as shown in the FIG., Such generation processes are: group by name, then the name to find the row with the same name the row values, It merged into one line, as described for aa name value, then <1 aa 2> and <2 aa 3> two lines merged into one line, and all the values ​​of id number value is written to a cell surface Gerry.

 

3. The next step is for the virtual table 3 to perform a Select statement:

(1) If you do select *, then the results should be returned virtual table 3, but the number of content-id and some units Gerry face multiple values, and relational database is based on the relationship of the cell is not It allows multiple values, so you see, perform a select * statement on the error.

(2) We look at the name column, each cell has only one data, so we select name, then there is no problem. Why the name column each cell has only one value, it is because we are used to group by the name column.

(3) then there is more data for id and the number of cells inside the case of how to do it? The answer is to use aggregation functions, aggregation function is used on a plurality of data input, a data output. The cout (id), sum (number), and each input is a function of the polymerization cell for each of multiple data.

(4)例如我们执行select name,sum(number) from test group by name,那么sum就对虚拟表3的number列的每个单元格进行sum操作,例如对name为aa的那一行的number列执行sum操作,即2+3,返回5,最后执行结果如下:

 (5)group by 多个字段该怎么理解呢:如group by name,number,我们可以把name和number 看成一个整体字段,以他们整体来进行分组的。如下图

(6)接下来就可以配合select和聚合函数进行操作了。如执行select name,sum(id) from test group by name,number,结果如下图:

Guess you like

Origin www.cnblogs.com/leduo/p/11979337.html