SQL --------------- GROUP BY function

Aggregate functions often need to add a GROUP BY statement, Aggregate function is often said poly and function, also called aggregate functions

GROUP BY statement commonly used with aggregate functions (COUNT, MAX, MIN, SUM, AVG), according to one or more columns of the result set grouping.

grammar:

select aggregate function (field),   from table Group  by   field

Build a table, get points, in order to facilitate comparison

 

 

 Grouped query banking statistics of the same name a few

SELECT  COUNT (field) AS number, a field from table Group  by field a

Which count in the field free to fill in, generally id

 

 

Possible error:

That field only and grouping queries can not aggregate functions

 

 

 You can be slightly modified:

Check bank group, and the total number of wage statistics

 

 

 The top one query

grammar:

SELECT  Top front query lines COUNT (field) AS number, a field from table Group  by field a

 

 

 And the sort order by a

Syntax: Field to be consistent

SELECT  Top front query lines COUNT (field) AS number, field A from table Group  by field A Order  by field A desc

 

 

 If not

 

 

 And where the words using a

Syntax: count () there is no limit, put consequently the line

SELECT  Top front query lines COUNT ( 0 ) AS number, field A from table where conditions Group  by field A Order  by field A desc

 

 Multi-table query

grammar:

SELECT table 1.name, COUNT (Table 2.aid) the AS the nums the FROM Table 2
 the INNER the JOIN Table. 1
 the ON Table 2.site_id = Table 1.id
 the GROUP  BY table 1.name;

 

 

the SELECT  *  from obgetest 
 -   grouping query Bank ,, which is the name of two obge 
the SELECT  COUNT (Gids) AS number, Bank from obgetest Group  by Bank 

- - As can be seen, when multiple fields, only to be grouped query fields that can not use aggregate functions 
the SELECT  COUNT (Gids) aS number, Bank, Gongzi from obgetest Group  by Bank 

- can modify the query packet banks, and the total wage statistics the total number of 
the SELECT  COUNT (Gids) aS number, Bank, SUM (Gongzi) AS total from obgetest Group  byBank 

-   and a top query, count field bank and placed inside the field of action consistent gids 
SELECT  top  . 5  COUNT (Bank) AS number, Bank from obgetest Group  by Bank 

-   one with the order by, the same number inquiry packet wages and in accordance with the reverse order, check before row 5 
- --- must pay attention field and packet field to be consistent ordering 
SELECT  Top  5  COUNT (REM) AS number, Gongzi from obgetest Group  by Gongzi Order  by Gongzi desc 
- - there is an error 
the SELECT  Top  5  COUNT (REM) ASNumber, Gongzi from obgetest Group  by Gongzi Order  by Gids desc 

- - Note that the syntax and the position where the words 
SELECT   COUNT ( 0 ) AS number, Gongzi from obgetest where Gongzi >  1000  Group  by Gongzi Order  by Gongzi desc

 

Guess you like

Origin www.cnblogs.com/obge/p/11718946.html