0

我有这个查询,我从三个表中选择

select 
    min(t.ReminderDt) as 'rem dt',  
    m.Group_Id, m.AccountNumber 
from 
    ACE_AccsLevelTran t, ACE_AccsLevelMaster m 
where 
    t.MasterAccNumber = m.AccountNumber 
group by  
    m.Group_Id, m.AccountNumber;

这导致:

rem dt | Group_Id| AccountNumber
--------------------------------    
2/8/2013 | 3 | 4216985
2/22/2013 | 4 | 4274863
2/7/2013 | 3 | 4366383
2/28/2013 | 4 | 7151712

如何仅获取 3 和 4 的最短日期的行,如结果 -

2/7/2013 | 3 | 4366383
2/22/2013 | 4 | 4274863
4

2 回答 2

3

只需从 group by 中删除 account_number 并用min()or包围它:max()select

select min(t.ReminderDt) as 'rem dt',  m.Group_Id, min(m.AccountNumber)
from ACE_AccsLevelTran t,     ACE_AccsLevelMaster m 
where t.MasterAccNumber=m.AccountNumber
group by  m.Group_Id

这将返回一个任意帐号。要获得具有最小值的row_number(),最好的方法是使用:

select *
from (select t.ReminderDt) as 'rem dt',  m.Group_Id, m.AccountNumber,
            row_number() over (partition by group_id order by reminderdt desc) as seqnum
      from ACE_AccsLevelTran t join ACE_AccsLevelMaster m 
           on t.MasterAccNumber=m.AccountNumber
     ) t
where seqnum = 1

此外,您应该学习在此查询中使用的 ANSI 标准 JOIN 语法。

于 2013-02-26T16:59:19.287 回答
-1

如果您的 accountNumber 也是唯一的,您可以这样做:

Select m.Group_Id ,X.MinReminderDT,m.AccountNumber 
from ACE_AccsLevelMaster m join(
select min(t.ReminderDt) as MinReminderDT,t.MasterAccNumber
from ACE_AccsLevelTran t
Group By t.MasterAccNumber) X on X.MasterAccNumber=m.AccountNumber
于 2013-02-26T17:05:35.160 回答