2011-07-03 62 views
1

嗨,我很難分組這些數據,因爲它沒有聚合函數。我有兩個表中的以下數據,我想通過PaymentId和display only 1 row of record加入。分組問題

enter image description here

問:
如何顯示在僅1 ROW GROUPBY CoursePaidForMonthYear最終結果。
我想從Payment.*, TutorCourseCommissions.* and CoursePaidForMonthYear column in same row displaying (September, October, November)

範例中得到的所有數據:

referenceId| TutorId| CoursePaidForMonthYear     | 
1   | 1019 | September, October, November OR 9,10,11| 

我的工作:

var result = from u in db.Users 
        join p in db.Payments on u.Id equals p.UserId 
        join tt in db.TutorCourseCommissions on p.Id equals tt.PaymentId into gtt 
         from tt in gtt.DefaultIfEmpty()      
        where u.Id == user.Id 
        GroupBy tt.CoursePaidForMonthYear ?? 
        select new { u, p, tt }; 

      foreach (var r in result) 
      { 
       Payment payment = new Payment();     
       payment.MonthToPay = (r.tt == null) ? null : common.GetMonthName(r.tt.CoursePaidForMonthYear.Month, true); 
       payment.Amount = r.p.Amount;      

       output.Add(payment); 
      } 
      return output; 

回答

1

你需要做的是組由用戶和支付幾個月,然後進行聚合在分組月份。在這種情況下,我使用String.Join()來組合來自佣金的不同月份。

這會給你的結果沿着{ User = "John Doe", Payment = ..., Months = "January, February" }

var result = from u in db.Users 
       where u.UserID == user.Id 
       join p in db.Payments on u.Id equals p.UserId 
       join comm in db.TutorCourseCommissions 
       on p.Id equals comm.PaymentId 
       group common.GetMonthName(comm.CoursePaidForMonthYear,true) 
       by new { User = u, Payment = p } into g 
       select new 
       { 
       User = g.Key.User, 
       Payment = g.Key.Payment, 
       //...select out other properties here... 
       Months = String.Join(", ", g.Distinct()) 
       }; 
0

製造一類關於你所需要的所有列的屬性,然後執行使用其實例進行選擇...

public TutorPayments 
{ 

public int UserID{ 
get; 
set; 
} 

public int PayType{ 
get; 
set; 
    } 

    public int TutorID{ 
    get; 
set; 
    } 

//and so on all columns property that you required 
} 

現在你可以通過這種方式創建它的實例讓您的查詢所有這些

var result = from u in db.Users 
       join p in db.Payments on u.Id equals p.UserId 
       join tt in db.TutorCourseCommissions on p.Id equals tt.PaymentId into gtt 
        from tt in gtt.DefaultIfEmpty()      
       where u.Id == user.Id 
       GroupBy tt.CoursePaidForMonthYear ?? 
       select new TutorPayments {UserID = u.id,PayType = p.id,TutorID = tt.TutorId, ............ };