Using group by on multiple columns
我理解EDOCX1的意义(0)
但是,
为了举例说明,假设我们有下表,与谁在一所大学就读什么科目有关:
1 2 3 4 5 6 7 8 9 10 11 | TABLE: Subject_Selection Subject Semester Attendee --------------------------------- ITB001 1 John ITB001 1 Bob ITB001 1 Mickey ITB001 2 Jenny ITB001 2 James MKB114 1 John MKB114 1 Erica |
当你只在主题栏上使用
1 2 3 | SELECT Subject, COUNT(*) FROM Subject_Selection GROUP BY Subject |
你会得到如下信息:
1 2 3 4 | Subject COUNT ------------------------------ ITB001 5 MKB114 2 |
…因为ITB001有5个条目,MKB114有2个条目
如果我们是
1 2 3 | SELECT Subject, Semester, COUNT(*) FROM Subject_Selection GROUP BY Subject, Semester |
我们会得到:
1 2 3 4 5 | Subject Semester COUNT ------------------------------ ITB001 1 3 ITB001 2 2 MKB114 1 2 |
这是因为,当我们按两列分组时,它会说"将它们分组,使所有具有相同主题和学期的人都在同一组中,然后计算每个组的所有聚合函数(计数、求和、平均值等)。在这个例子中,我们通过一个事实来证明,当我们计算它们时,有三个人在第一学期做ITB001,还有两个人在第二学期做ITB001。做mkb114的两个人都在第一学期,所以第二学期没有行(没有数据适合"mkb114,第二学期"组)
希望这是有道理的。
1 2 3 4 | SELECT column_name, aggregate_function(column_name) FROM TABLE_NAME WHERE column_name operator VALUE GROUP BY column_name; |
记住以下顺序:
1) SELECT (is used to select data from a database)
2) FROM (clause is used to list the tables)
3) WHERE (clause is used to filter records)
4) GROUP BY (clause can be used in a SELECT statement to collect data
across multiple records and group the results by one or more columns)5) HAVING (clause is used in combination with the GROUP BY clause to
restrict the groups of returned rows to only those whose the condition
is TRUE)6) ORDER BY (keyword is used to sort the result-set)
如果您使用的是聚合函数,那么您可以使用所有这些函数,并且这是它们必须设置的顺序,否则您会得到一个错误。
聚合函数为:
MIN returns the smallest value in a given column
SUM returns the sum of the numeric values in a given column
AVG returns the average value of a given column
COUNT returns the total number of values in a given column
COUNT(*) returns the number of rows in a table