Home > Database > Mysql Tutorial > How to Find the Most Recent Record for Each Group with Non-Zero Checks in SQL Server?

How to Find the Most Recent Record for Each Group with Non-Zero Checks in SQL Server?

Barbara Streisand
Release: 2025-01-08 13:27:42
Original
464 people have browsed it

How to Find the Most Recent Record for Each Group with Non-Zero Checks in SQL Server?

Efficiently Retrieving Latest Records with Non-Zero Check Values in SQL Server

This article demonstrates how to retrieve the most recent record for each group in a SQL Server table, specifically focusing on records where the 'checks' column value is greater than zero. Let's consider a sample table with the following structure:

<code>| GroupID | RecordDate | CashAmount | CheckAmount |
|---|---|---|---|
| 1 | 2013-01-01 | 0 | 0 |
| 2 | 2013-01-01 | 0 | 800 |
| 1 | 2013-01-03 | 0 | 700 |
| 3 | 2013-01-01 | 0 | 600 |
| 1 | 2013-01-02 | 0 | 400 |
| 3 | 2013-01-05 | 0 | 200 |</code>
Copy after login

Our goal is to obtain the following result set:

<code>| GroupID | RecordDate | CheckAmount |
|---|---|---|
| 2 | 2013-01-01 | 800 |
| 1 | 2013-01-03 | 700 |
| 3 | 2013-01-05 | 200 |</code>
Copy after login

Here's how to achieve this using a SQL query:

First, we identify the maximum RecordDate for each GroupID where CheckAmount is greater than 0:

<code class="language-sql">SELECT GroupID, MAX(RecordDate) AS MaxRecordDate
FROM YourTable
WHERE CheckAmount > 0
GROUP BY GroupID;</code>
Copy after login

Then, we join this result back to the original table to retrieve the corresponding CheckAmount:

<code class="language-sql">SELECT yt.GroupID, yt.RecordDate, yt.CheckAmount
FROM YourTable yt
INNER JOIN (
    SELECT GroupID, MAX(RecordDate) AS MaxRecordDate
    FROM YourTable
    WHERE CheckAmount > 0
    GROUP BY GroupID
) AS MaxDates ON yt.GroupID = MaxDates.GroupID AND yt.RecordDate = MaxDates.MaxRecordDate;</code>
Copy after login

This query efficiently filters for non-zero check amounts and selects only the most recent record for each group. Remember to replace YourTable with the actual name of your table. Using descriptive column names (like GroupID and CheckAmount) is strongly recommended for better code readability and maintainability.

The above is the detailed content of How to Find the Most Recent Record for Each Group with Non-Zero Checks in SQL Server?. 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