SQL intermediate window-functions group-by aggregation

How to Get First and Last Values in Each Group in SQL?

First and Last in Group is a SQL query that this sql query retrieves the first and last order dates for each customer by grouping the orders.. Formula Genius generates and validates this formula automatically from a plain-English prompt.

Discover how to efficiently extract the first and last records for each group in your SQL data, enhancing your data analysis capabilities.

The Formula

Prompt

"Get the first and last values within each group (e.g. first and last order per customer) using window functions or subqueries"

SQL
SELECT customer_id, MIN(order_date) AS first_order, MAX(order_date) AS last_order FROM orders GROUP BY customer_id;

This SQL query retrieves the first and last order dates for each customer by grouping the orders.

Step-by-Step Breakdown

  1. SELECT the customer_id and aggregate functions for first and last orders.
  2. Use MIN() to find the earliest order date and MAX() for the latest.
  3. FROM the orders table to specify the data source.
  4. GROUP BY customer_id to ensure results are grouped per customer.

Edge Cases & Warnings

  • Customers with only one order will show the same date for first and last.
  • If there are no orders for a customer, they will not appear in the results.
  • Handling NULL values in order_date may affect the output.
  • Multiple orders on the same date will return that date for both first and last.

Examples

Prompt

"Customer ID: 1 with orders on 2023-01-01 and 2023-01-05"

SQL
First Order: 2023-01-01, Last Order: 2023-01-05
Prompt

"Customer ID: 2 with a single order on 2023-01-10"

SQL
First Order: 2023-01-10, Last Order: 2023-01-10

Frequently Asked Questions

What if a customer has no orders?

They will not be included in the result set.

Can I modify this query for other groupings?

Yes, simply change the GROUP BY clause to the desired grouping.

How do I include additional columns in the result?

You can add more columns in the SELECT statement and adjust the GROUP BY clause accordingly.

Can't find what you need?

Describe any formula in plain English and Formula Genius will generate, explain, and validate it — instantly.