You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单分组数据行处理: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 attribute groups rows so we handle each attribute separately.
  • ORDER BY date DESC ensures the row with the latest date gets the rank 1.
  • If multiple rows share the same maximum date for an attribute, ROW_NUMBER() will pick just one (randomly, unless you add more columns to the ORDER BY to break ties). If you want to keep all tied rows, swap ROW_NUMBER() with RANK() or DENSE_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 date column is a proper date/time data type (not a string) — this ensures MAX() works as expected.
  • If you need to exclude NULL values for attribute or date, add a WHERE clause in the inner query (e.g., WHERE attribute IS NOT NULL AND date IS NOT NULL).

内容的提问来源于stack exchange,提问作者maijanen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 06:42:40