sql - Select most recent InstanceID base on max end date -


i trying pull memberinstance table based on max dateend. if null want pull still ongoing. using sql server.

select memberinstanceid
table
group memberid
having max(isnull(date_end, '2099-12-31'))

this query above doesnt work me. have tried different ones , have gotten return separate instances, not 1 max date.

below table looks like.

memberid     memberinstanceid     datestart     dateend
     2                      abc12                 2013-01-01   2013-12-31
     4                      abc21                 2010-01-01   2013-12-31
     2                     abc10                  2015-01-01       null
     4                      abc19                 2014-01-01   2014-10-31

i expect results this

memberinstanceid
abc10
abc19

i have been trying figure out how have not had luck. appreciated. thanks

i think need following:

select memberid, memberinstanceid table t (     -- dateend null...     dateend null     or (         -- ...or pick latest dateend member...         dateend = (             select max(dateend)             table             memberid = t.memberid         )         -- ... , check there's not null entry dateend member         , not exists (             select 1             table             memberid = t.memberid             , dateend null         )     ) ) 

the problem approach if there multiple rows match each member, i.e. multiple null rows same memberid, or multiple rows same dateend same memberid.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -