开发者

sql query sub select on itself confusion

开发者 https://www.devze.com 2022-12-20 02:27 出处:网络
I\'m trying to write a sql statement which returns bad rows from my table. I have a table with rows: Key|Date|Indicator

I'm trying to write a sql statement which returns bad rows from my table. I have a table with rows:

Key | Date | Indicator

1 | 10/10/08 | SE

1 | 10/11/09 | CB

1 | 10/12/09 | CE

1 | 10/13/09 | TR

2 | 1/1/09 | SE

3 | 10/10/08 | SE

3 | 10/13/09 | CE

3 | 10/15/09 | SL

So what I want returned would be all rows where a key has an indicator of CE then I want the row that is exactly after it date wise.

EX. my result would then开发者_如何学Python be:

1 | 10/13/09 | TR

3 | 10/15/09 | SL

My problem is I can't figure out how to join the table on itself with the conditions listed above. Please help with any suggestions.


This should give you all of the rows even if a CE occurs more than once for a key.

select t1.*
from myTable t1
inner join 
    (select t2.[key], min(t2.date) minDate   
    from myTable t2   
    inner join (   
      select CE.[key], CE.date     
      from myTable CE   
      where CE.indicator = 'CE'  
      ) as CEs 
    on CEs.[key] = t2.[key] 
    and CEs.date < t2.date 
    group by t2.[key]) t2s
on t2s.[key] = t1.[key]
and t1.date = t2s.minDate
order by 1, 2


Probably not very fast, but my first guess.

select * from table where 'CE' = 
(select top(1) indicator from table 
    t1 where t1.date < table.date and t1.key = table.key order by date desc)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号