SQL - 根据2列和条件返回唯一行

时间:2017-09-12 22:53:50

标签: sql group-by distinct hsqldb

我有一个HSQLDB表,数据为

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也相同,则返回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 

但是查询失败了,因为我不能对不在group by(lastname,state等)中的列使用聚合函数。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

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
             );

答案 1 :(得分:0)

我不熟悉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