简体   繁体   English

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

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

I have a table on HSQLDB with data as 我在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

How can i write a query that gives me rows that have distinct values in Account and Opendate columns, having the maximum Baldate. 我该如何写一个查询,使我的行在Account和Opendate列中具有不同的值,并且具有最大Baldate。 If Baldate is also same, then return the first row ordered by Id. 如果Baldate也相同,则返回ID排序的第一行。

So the resultset should contain 因此结果集应包含

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

I have gotten this far. 我已经走了这么远。

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

But the query fails since I cannot use an aggregate function for columns not in group by (lastname, state etc). 但查询失败,因为我无法对不在分组依据(姓,状态等)中的列使用聚合函数。 How can I resolve this? 我该如何解决?

HSQLDB supports correlated subqueries, so I think this will work: 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
             );

I'm not familiar with hslqdb, so this is just ANSI. 我不熟悉hslqdb,所以这只是ANSI。 I see that it doesn't support analytical functions, which would make life easier. 我看到它不支持分析功能,这会使生活更轻松。

If it works the other answer is a lot cleaner. 如果可行,另一个答案会更清洁。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM