Select 最近两年的所有记录和特定状态的最短日期

Select all records for last two years and minimum date for specific status

过去几天我一直在处理这个问题,但无论我做什么,我都会得到同样错误的记录集。

表格:

帐号

id | Customer | dateOpened  
--------------------------
1  | ConAgra  | 11/01/2013  
2  | Fedex    | 06/21/2014  

案件状态

id | caseStatus  
---------------  
1  | A  
2  | B  
3  | M  
4  | C  
5  | H  
6  | W  

m_account_caseStatus

AccountID | caseStatusID | startDate | endDate  
----------------------------------------------  
1         | 2            | 11/01/2013| 12/15/2013  
1         | 1            | 12/15/2013| 2/03/2014  
1         | 2            | 2/03/2014 | 3/17/2014  
2         | 6            | 6/21/2014 | 8/25/2014  
2         | 3            | 8/25/2014 | 10/21/2014  
2         | 1            | 10/21/2014| NULL  

我需要的是最近两年开设的所有账户以及最早的startDate 和caseStatus,其中caseStatus 为A 或B(不是同时为A 或B,以先指定的为准)。我一直得到的只是 minDate 为 A 或 B 的帐户,这要少得多。

select 
    c.ID, c.Customer, cs.caseStatus  
from 
    m_account_caseStatus m 
left outer join 
    caseStatus cs on m.caseStatusID = cs.ID 
left outer join 
    Account a on m.accountID = a.ID   
where 
    a.dateOpened >= dateAdd(yyyy, -2, getDate()) 
    and caseStatus IN ('A','B') 
    and (a.startDate = (select min(startdate)  
                        from m_account_caseStatus sub1  
                        where sub1.accountID = c.ID))  

我已经多次重新处理查询,移动子查询和 caseStatus,但我总是只得到它们以 A 或 B 状态开始的情况,而不是所有情况和 date/status 首先是 A 或 B。

感谢您提供的任何帮助。

declare @year2 datetime = dateAdd(yyyy, -2, getdate())
select accountID from
(
    -- all A or B accounts withing 2 years
    -- num = 1 (2,3..) is the 1st (2nd, 3rd...) date when account got A or B status
    select 
        m.accountID,
        row_number() over (partition by m.accountID order by startDate) as num
    from 
        m_account_caseStatus m 
        join 
        Account a on m.accountID = a.ID 
    where 
    a.dateOpened >= year2
    and m.caseStatusId in (1,2)
) T
where T.num = 1
;with c as 
(
  select accountID,caseStatusID,startDate,
  ROW_NUMBER() OVER (PARTITION BY accountID ORDER BY startDate DESC) rnk
  from m_account_caseStatus
)

select c.accountID,a.Customer,a.dateOpened,c.caseStatusID,cs.caseStatus,c.startDate
from c 
join Account a on a.ID=c.accountID
join caseStatus cs on cs.ID=c.caseStatusID
where rnk=1 and a.dateOpened>=dateAdd(yyyy, -2, getDate())