MySQL grouping function MAX, aggregate functions GROUP BY query connection

Take a look at the table for the practice of what was in it.

SELECT * FROM shop ORDER BY article;

+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|       1 | A      |  3.45 |
|       1 | B      |  3.99 |
|       2 | A      | 10.99 |
|       3 | B      |  1.45 |
|       3 | C      |  1.69 |
|       3 | D      |  1.25 |
|       4 | D      | 19.95 |
+---------+--------+-------+

 

  • Find the price (price) the most expensive article:

Method a: selecting the maximum value MAX function polymerization

SELECT MAX(price) FROM shop;

 

Method 2: ORDER BY sorting, "LIMIT 1" to display only the first line

SELECT article, dealer, price
FROM shop
ORDER BY price DESC
LIMIT 1;

 

Method three: Use the left connection

SELECT s1.article, s1.dealer, s1.price
FROM shop s1
LEFT JOIN shop s2 ON s1.price < s2.price
WHERE s2.article IS NULL;

 

  • Find the highest price of each article of.

Selecting the maximum value MAX function, the packet to the article with GROUP BY.

Note the following when used with polymerizable function groups and functions, grouped GROUP BY aggregate functions can not be modified fields. Example, the following article is a GROUP BY, article can not be when the SELECT MAX ().

SELECT article, MAX(price) AS price FROM   shop
GROUP BY article ORDER BY article;

 

Using aggregate functions with GROUP BY has a weakness, if we want to choose article, dealer, MAX (price), but only calculate the maximum packet article, which is not.

Note: The following back GROUP BY SQL statement only article.

SELECT article,dealer,MAX(price) AS price FROM shop
GROUP BY article ORDER BY article;

The following statement is correct, but did not achieve our goal only in accordance with article grouping seeking maximum.

SELECT article,dealer,MAX(price) AS price FROM shop
GROUP BY article,dealer ORDER BY article;

 

GROUP BY and aggregate functions can not, the query is connected to the timing of large fame.

Here are your inside connections appearances. En is INNER JOIN, you can not write INNER.

The same demand: for of each article, find the highest price.

En

SELECT s1.article, dealer, s1.price
FROM
shop s1 JOIN ( SELECT article, MAX(price) AS price FROM shop GROUP BY article) AS s2 ON s1.article = s2.article AND s1.price = s2.price ORDER BY article;

 

Left connection (LEFT JOIN) can also accomplish this goal.

SELECT s1.article, s1.dealer, s1.price
FROM shop s1
LEFT JOIN shop s2 ON s1.article = s2.article AND s1.price < s2.price
WHERE s2.article IS NULL
ORDER BY s1.article;

 

Reference connection

MySQL official website

https://dev.mysql.com/doc/refman/8.0/en/example-maximum-column-group-row.html

Guess you like

Origin www.cnblogs.com/majestyking/p/11260022.html