Improved a Group By

1. The first review under the Basics:


Group By the polymerization of the data packet, often accompanied by having to use. having a single record may be processed and to be processed in units of group.

Statement:

SELECT col
FROM table
[WHERE]
[GROUP BY]
[HAVING]
[ORDER BY [ASC]|[DESC]]

Generating a data set 1.FROM clause
2.WHERE clause 1 generates filtered data set
3.GROUP BY clause 2 polymerizable generated data sets
4.HAVING clause filter 3 generates the data set
5.SELECT clause 4 the results do the conversion
6.ORDER BY clause 5 transformed data set is sorted

 

Field but not in the SELECT clause must use a GROUP BY clause aggregate function.
Aggregate function is to perform a set value calculation and returns a single worth deterministic functions, such as COUNT, SUM, AVG, MIN, MAX, VAR_POP, VAR_SAMP like.

 

 

2. Body:


SQL-92 standard from the beginning, the mandatory use of a GROUP BY clause, most manufacturers also have to comply with the mainstream, that is: SELECT field, either already listed in a GROUP BY, or the use of a polymerization function.

Such as: user table, order form, we want to see the consumption of each user, that is, by order userid query packet data, what we really want is:

SELECT u.userid,u.username,u.city,SUM(o.OrderTatal) AS total
FROM user u LEFT JOIN order o ON u.userid=o.userid
GROUP BY u.userid

 

Unfortunately, this statement does not meet the requirements of GROUP BY, SELECT must appear, but did not use the field u.username aggregate functions, u.city added to the GROUP BY clause, we really do not care whether these two fields polymerization, these two fields to our desired result not be very meaningful, but will not write error, so often written as:

SELECT u.userid,u.username,u.city,SUM(o.OrderTatal) AS total
FROM user u LEFT JOIN order o ON u.userid=o.userid
GROUP BY u.userid,u.username,u.city

 

This column is called functionally dependent column, write also to meet the requirements, but a shortage is a summary of the conditions we really care about is flooded. If the time interval a little longer or a little complicated sentence, you are sure to distinguish fact redundant functions dependent column it? We Yaoan summary of each user, but also to distinguish between specific city? Sometimes you have to understand the whole basis of the query.


To improve this type of GROUP BY, summary conditions do not allow real concern is submerged. Improved after the statement:

SELECT u.userid,u.username,u.city,o.total
FROM user u
LEFT JOIN
(SELECT t.userid,SUM(t.OrderTotal) AS Total FROM Order AS t GROUP BY t.userid) AS o
ON u.userid=o.userid;

 

Guess you like

Origin www.cnblogs.com/GGGong/p/11898280.html