简体   繁体   中英

Take only the first that satisfies the second condition

I have ac# object with date field and foreign key. I have created one double index on these fields.

public class Session : DbObject
{        
    [DataMember]
    [Column(TypeName = "date")]
    [Index(IsUnique = false, Order = 2)]
    public DateTime Date { get; set; }

    [DataMember]
    [Index(IsUnique = false, Order = 1)]
    public int PatientId { get; set; }

    [DataMember]
    public Patient Patient { get; set; }     
}

I need to take a list from the 'Sessions' as follow: I have a list of patients ids and a date. I need to get one Session for each patient that its date is newest from all the rest.

something like this:

SELECT * FROM Sessions WHERE PatientId IN (1, 2, ...) AND TOP(Date < SOME_DATE)

I know this query is nonsense. It just to clarify my intention.

***It is important to use the indexes because this table is huge.

If it is possible, I would like to know if I can write it in c# and entity framework.

Thanks a lot!

***It is important to use the indexes because this table is huge.

The LINQ query would look something like:

var ids = new List<int>() { 1, 2, 3 };
var dt = DateTime.Now;
var q = from s in db.Sessions
        where ids.Contains(s.Id)
            && s.Date > dt
        group s by s.PatientId into byPatientId
        select byPatientId.OrderBy(s => s.Date).Take(1);

But that's perhaps not the most efficient query. If that's too slow, you might want to consider a store query instead:

db.Sessions.FromSql(@"
with q as 
( 
   select Date, 
          PatientId, 
          row_number() over (partition by PatientId order by Date desc) rn
   where PatientId in (1,2,3,5,6,3)
     and Date > @d
   from Sessions
)
select Date, PatientId
from q
where rn = 1
", dt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM