2015-02-24 16 views
1

我有这样的表。(VisitType是动态的)透视表使用LINQ

PersonelId  VisitDate  VisitTypeId 
1     2015-02-24  A 
2     2015-02-23  S 
2     2015-02-24  D 
4     2015-02-22  S 
2     2015-02-22  A 
2     2015-02-22  B 
3     2015-02-23  A 
1     2015-02-23  A 
1     2015-02-24  D 
4     2015-02-24  S 
4     2015-02-22  S 
2     2015-02-22  S 
3     2015-02-24  D 

我想这个使用LINQ的支点如下。

VisitDate PersonelId  A  S  D  B 
2015-02-22 4    0  2  0  0 
2015-02-22 2    1  1  0  0 
2015-02-23 2    0  1  0  0 
2015-02-23 3    1  0  0  0 
2015-02-23 1    1  0  0  0 
2015-02-24 1    1  0  1  0 
2015-02-24 2    0  0  1  0 
2015-02-24 4    0  1  0  0 
2015-02-24 3    0  0  1  0 

我用这个LINQ

var d = (from f in _db.Visits 
       group f by new {f.VisitDate, f.PersonnelId } 
        into myGroup 
        where myGroup.Count() > 0 
        select new 
        { 
         myGroup.Key.VisitDate, 
         myGroup.Key.PersonnelId, 
         subject = myGroup.GroupBy(f => f.VisitTypeId).Select 
         (m => new { Sub = m.Count(), Score = m.Sum(c => c.Amount) }) 
        }).ToList(); 

它由日期和企业人事ID分组,但不要指望从每一个VisitType项目。像下面

var VisTyp= (from VT in _db.VisitType select new{VisType=VT.VisitType}).ToList(); 

然后使用以下

//static headers version 
var qry = Visits.GroupBy(v=>new{v.VisitDate, v.PersonelId}) 
    .Select(g=>new{ 
      VisitDate = g.Key.VisitDate, 
      PersonelId = g.Key.PersonelId, 
      A = g.Where(d=>d.VisitTypeId=="A").Count(), 
      B = g.Where(d=>d.VisitTypeId=="B").Count(), 
      D = g.Where(d=>d.VisitTypeId=="D").Count(), 
      S = g.Where(d=>d.VisitTypeId=="S").Count() 
      }); 

//dynamic headers version 
var qry = Visits.GroupBy(v=>new{v.VisitDate, v.PersonelId}) 
    .Select(g=>new{ 
      VisitDate = g.Key.VisitDate, 
      PersonelId = g.Key.PersonelId, 
      subject = g.GroupBy(f => f.VisitTypeId) 
         .Select(m => new { Sub = m.Key, Score = m.Count()}) 
      }); 

回答

2

试试这个。

var d = (from f in _db.Visits 
    group f by new {f.VisitDate, f.PersonnelId } into myGroup 
    where myGroup.Count() > 0 
    select new 
    { 
      VisitDate = myGroup.Key.VisitDate, 
      PersonnelId = myGroup.Key.PersonnelId, 
      subject=myGroup.Count(t => VisTyp.Contains(t.VisitType)) 
    }).ToList(); 
+0

谢谢,但VisitType是动态的(它是另一张表的外键) – 2015-02-24 07:09:08

+0

您的意思所说的“VisitType is dynamic”? – 2015-02-24 07:12:22

+0

我有两个模型,访问和VisitType。该访问类型是访问表中的外键 – 2015-02-24 07:18:09

0

首先提取动态访问类型的人: