Linq查询使用Group by和Joins

时间:2016-09-27 19:08:02

标签: c# linq

我有两张桌子:

广告

--------------------------------------------------------|
 BId   | Name | Link | Image | AltText| Target | BActive|
--------------------------------------------------------
 |1    | hello| http| a.jpg  |helloimg|        |    1   |
--------------------------------------------------------

跟踪

------------------------------------------------------
|TId   | BId| ICount| CCount| CreateDate             | 
------------------------------------------------------
|1     |  1 | 102   |  300  |  2015-11-17 00:00:000  |
|2     |  1 | 182   |  100  |  2015-11-14 00:00:000  |
|3     |  1 | 192   |  200  |  2015-11-12 00:00:000  |
------------------------------------------------------

我希望在2015-11-12和2015-11-15之间找到每个BId的ICount和CCound的总和。

以下是我尝试的代码:

from p in Bannertables
join q in BannerTrackings
on p.BannerId equals q.BannerId
group p by p.BannerId into myTab
select new { 
    BannerId = myTab.Key,
    ImpressionCount = myTab.Sum( x=> x.ImpressionCount),
    ClickCount = myTab.Sum(x => x.ClickCount)
};

如何根据我指定的日期范围对结果进行排序?

1 个答案:

答案 0 :(得分:1)

将以下where添加到您的查询中:

var d1 = new DateTime(2015, 11, 12);
var d2 = new DateTime(2015, 11, 15);
var query=from p in Bannertables
          join q in BannerTrackings
          on p.BannerId equals q.BannerId
          where q.CreateDate>=d1 && q.CreateDate<=d2
          group q by p.BannerId into myTab
          select new { 
                       BannerId = myTab.Key,
                       ImpressionCount = myTab.Sum( x=> x.ImpressionCount),
                       ClickCount = myTab.Sum(x => x.ClickCount)
                      };

更新

如果您想要访问Banner的属性,请将其包含在组中,如下所示:

var d1 = new DateTime(2015, 11, 12);
var d2 = new DateTime(2015, 11, 15);
var query=from p in Bannertables
          join q in BannerTrackings
          on p.BannerId equals q.BannerId
          where q.CreateDate>=d1 && q.CreateDate<=d2
          group new{Banner=p,Tracking=q} by p.BannerId into myTab
          select new { 
                       BannerId = myTab.Key,
                       Bannername=myTab.Select(e=>e.Banner.Name).FirstOrDefault(),
                       ImpressionCount = myTab.Sum( x=> x.Tracking.ImpressionCount),
                       ClickCount = myTab.Sum(x => x.Tracking.ClickCount)
                      };

但如果您只想要横幅名称,那就更好了:

var d1 = new DateTime(2015, 11, 12);
var d2 = new DateTime(2015, 11, 15);
var query=from p in Bannertables
          join q in BannerTrackings
          on p.BannerId equals q.BannerId
          where q.CreateDate>=d1 && q.CreateDate<=d2
          group q by new {p.BannerId,p.Name} into myTab
          select new { 
                       BannerId = myTab.Key.BannerId,
                       BannerName=myTab.Key.Name,
                       ImpressionCount = myTab.Sum( x=> x.ImpressionCount),
                       ClickCount = myTab.Sum(x => x.ClickCount)
                      };