0

我创建了这个查询,但我不知道如何找到最后一个 date_attribution

var usertmp = from user in entity.inv_utilisateur
              join userbadgetmp in entity.inv_utilisateur_badge on user.u_id equals userbadgetmp.u_id into gj
              from userbadge in gj.DefaultIfEmpty()

              select new UserEJ
              {
                  u_id = (int) user.u_id,
                  name = user.name,
                  date_attrib =  userbadge.date_attribution // here I want find the last date
              };

例如,如果我有这 2 个表:

inv_utilisateur                                inv_utilisateur_badge
u_id          name                               u_id           date_attribution
1             name1                              1              20130911
                                                 1              20130807
2             name2                              2              20120608
3             name3 

我需要结果

u_id               name             date_attribution
1                  name1            20130911
2                  name2            20120608
3                  name3            

编辑 1

字段的类型是:u_id:int,name:string,date_attribution:datetime

4

2 回答 2

1

很抱歉我的回答,但我没有在 from 子句中使用:

var usertmp = entity.inv_utilisateur
    .Join
    (
        entity.inv_utilisateur_badge,
        x=>x.u_id,
        x=>x.u_id,
        (user,userbadge) => new 
        {
            u_id = user.u_id, 
            name = user.name, 
            date_attrib = userbadge.date_attribution
        }
    )
    .GroupBy(x=>new {x.u_id,x.name})
    .Select
    (
        x => new 
        {
            x.Key.u_id,
            x.Key.name,
            date_attrib = x.Max(z=>z.date_attrib)
        }
    );
于 2013-09-11T15:48:38.183 回答
1
var usertmp = from user in entity.inv_utilisateur
              join userbadgetmp in entity.inv_utilisateur_badge on user.u_id equals userbadgetmp.u_id into gj
              from userbadge in gj.DefaultIfEmpty()
              group userbadge by new{user.u_id, user.name} into g
              select new UserEJ {
                 u_id = (int)g.Key.u_id,
                 name = g.Key.name,
                 date_attrib = g.Max(x => x!= null ? x.date_attribution : <a defaultvalue>)
              }

你也可以

var usertmp = from user in entity.inv_utilisateur
              let max_dt = (from userbadge in entity.inv_utilisateur_badge
                            where user.u_id == userbadge.u_id
                            select userbadge.date_attribution).Max()//??someDefaultvalue if you don't want null
              select new UserEJ {
                 u_id = user.u_id,
                 name = g.name,
                 date_attrib = max_dt
              }
于 2013-09-11T15:58:06.777 回答