选择过去两年的所有记录和特定状态的最短日期

时间:2015-01-14 14:29:25

标签: sql sql-server tsql

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

表:

帐户

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

CaseStatus

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(不是两者都有,不管是先分配的)。我一直得到的只是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状态开始而不是所有情况和日期/状态的情况它是第一个A或B.

感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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