SQL - Return 基于 2 列和条件的唯一行

SQL - Return unique rows based on 2 columns and a condition

我在 HSQLDB 上有一个 table,数据为

Id   Account    Opendate    Baldate      LastName ........ State
1    1234       040111      041217       Jackson           AZ 
2    1234       040111      051217       James             FL 
3    2345       050112      061213       Thomas            CA
4    2345       050112      061213       Kay               DE

我如何编写一个查询,为我提供在 Account 和 Opendate 列中具有不同值且具有最大 Baldate 的行。如果 Baldate 也相同,则 return 第一行按 Id 排序。

所以结果集应该包含

Id   Account    Opendate    Baldate      LastName........State
2    1234       040111      051217       James           FL
3    2345       050112      061213       Thomas          CA

我已经走到这一步了。

select LastName,...,State, max(BalDate) from ACCOUNTS group by Account, Opendate 

但是查询失败了,因为我不能对不在分组依据(姓氏、州等)中的列使用聚合函数。我该如何解决这个问题?

HSQLDB 支持相关子查询,所以我认为这会起作用:

select a.*
from accounts a
where a.id = (select a2.id
              from accounts a2
              where a2.account = a.account and a2.opendate = a.opendate
              order by baldate desc, id asc
              limit 1
             );

我不熟悉 hslqdb,所以这只是 ANSI。我看到它不支持分析功能,这会让生活更轻松。

如果有效,其他答案会更清晰。

SELECT ACC_T1.Id,
       ACC_T1.Opendate,
       ACC_T1.Baldate
       ACC_T1.LastName,
       ...
       ACC_T1.State
  FROM Account_Table AS ACC_T1
 INNER
  JOIN (SELECT account,
               OpenDate,
               MAX(BalDate) AS m_BalDate
          FROM AccountTable
         GROUP
            BY account,
               OpenDate
       ) AS SB1
    ON ACC_T1.Account = SB1.Account
   AND ACC_T1.OpenDate = SB1.OpenDate
   AND ACC_T1.BalDate = SB1.m_BalDate
 INNER
  JOIN (SELECT account,
               OpenDate,
               BalDate,
               MIN(id) AS m_id
          FROM Account_Table
         GROUP
            BY account,
               OpenDate,
               BalDate
       ) AS SB2
    ON ACC_T1.Account = SB2.Account
   AND ACC_T1.OpenDate = SB2.OpenDate
   AND ACC_T1.BalDate = SB2.BalDate
   AND ACC_T1.id = SB2.m_id