单分组数据行处理:SQL Developer中获取每个属性最大操作日期的查询语句咨询
Got it, let's figure out how to write this SQL query for you. Your goal is to pull one row per attribute from the actions table, and each row should be the one with the latest (maximum) date for that attribute. Here are two solid approaches that work perfectly in SQL Developer:
Method 1: Window Functions (Clean & Modern)
This is my preferred method because it's readable and handles tie scenarios easily. We'll use ROW_NUMBER() to assign a rank to each row within the same attribute, sorted by date in descending order. Then we just filter for the top-ranked row per attribute.
SELECT attribute, date, -- Include any other columns you need from the actions table your_other_column1, your_other_column2 FROM ( SELECT attribute, date, your_other_column1, your_other_column2, -- Rank rows per attribute, newest date first ROW_NUMBER() OVER (PARTITION BY attribute ORDER BY date DESC) AS row_rank FROM actions ) ranked_actions WHERE row_rank = 1;
Quick Notes:
PARTITION BY attributegroups rows so we handle each attribute separately.ORDER BY date DESCensures the row with the latest date gets the rank1.- If multiple rows share the same maximum date for an attribute,
ROW_NUMBER()will pick just one (randomly, unless you add more columns to theORDER BYto break ties). If you want to keep all tied rows, swapROW_NUMBER()withRANK()orDENSE_RANK().
Method 2: Subquery + Join (Great for Older Databases)
If you're working with a database that doesn't support window functions (though SQL Developer definitely does), this approach first grabs the maximum date for each attribute, then joins back to the actions table to get the full row data.
SELECT a.attribute, a.date, a.your_other_column1, a.your_other_column2 FROM actions a INNER JOIN ( -- Get the latest date for each attribute SELECT attribute, MAX(date) AS latest_date FROM actions GROUP BY attribute ) latest_dates ON a.attribute = latest_dates.attribute AND a.date = latest_dates.latest_date;
Quick Notes:
- This query will return all rows that have the maximum date for an attribute (if there are ties). If you only want one row per attribute even when ties exist, you'll need to add extra logic (like picking the max value of another column) or use the window function method instead.
Bonus Tips:
- Double-check that your
datecolumn is a proper date/time data type (not a string) — this ensuresMAX()works as expected. - If you need to exclude NULL values for
attributeordate, add aWHEREclause in the inner query (e.g.,WHERE attribute IS NOT NULL AND date IS NOT NULL).
内容的提问来源于stack exchange,提问作者maijanen

