我有这个查询,我从三个表中选择
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
答案 0 :(得分:3)
只需从群组中移除account_number,然后在min()
行上使用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语法。
答案 1 :(得分:-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