Home > Database > Mysql Tutorial > body text

How to Retrieve the First and Last Records from Grouped Results in MySQL?

Patricia Arquette
Release: 2024-11-10 06:22:02
Original
810 people have browsed it

How to Retrieve the First and Last Records from Grouped Results in MySQL?

Retrieving the First and Last Records from Grouped Results in MySQL

In MySQL, fetching the first and last records of a grouped result set while applying aggregate functions can be challenging. Consider the following query:

SELECT MIN(low_price), MAX(high_price), open, close
FROM symbols
WHERE date BETWEEN (.. ..)
GROUP BY YEARWEEK(date)
Copy after login

This query groups the data by week and calculates the minimum low price, maximum high price, open, and close values for each week. However, it does not provide the first and last records within each group.

To achieve this, one approach is to use the GROUP_CONCAT and SUBSTRING_INDEX functions:

SUBSTRING_INDEX(GROUP_CONCAT(CAST(open AS CHAR) ORDER BY datetime), ',', 1) AS open
SUBSTRING_INDEX(GROUP_CONCAT(CAST(close AS CHAR) ORDER BY datetime DESC), ',', 1) AS close
Copy after login

This solution allows you to concatenate all the open and close values for each group, separated by commas, and then extract the first and last values using SUBSTRING_INDEX. This approach avoids expensive subqueries and can be more efficient for this specific problem.

Refer to the MySQL documentation for more information on GROUP_CONCAT and SUBSTRING_INDEX functions. Additionally, you can explore other options such as using window functions or user-defined functions, depending on the specific requirements of your query.

The above is the detailed content of How to Retrieve the First and Last Records from Grouped Results in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template