更好的Linq GroupBy

时间:2012-10-10 14:05:53

标签: sql sql-server linq

我们正在制作一个广告平台并编写一个负责投放广告的大查询,有一些标准可以向消费者投放广告,其中一个标准是广告系列每日预算,所以我们正在做的是我们按个别广告进行分组以获取展示次数和消费费用,然后按广告系列进行分组,从而产生以下查询:

  (from a in AdCreative
       join h in AdHit on a.ID equals h.AdID into gh
       join l in AdGroup_Location on a.AdGroupID equals l.AdGroupID into gj
       from subloc in gj.DefaultIfEmpty()
       from subhits in gh.DefaultIfEmpty()
       where a.AdDimensionID == 7 && 
             (subloc == null || subloc.LocationID == 23)
       select new {
           ID = a.ID,
           Name = a.Name,
           Spent = (subhits.AdDimension != null) ? ((double)subhits.AdDimension.Credit / 1000 ) : 0,
           CampaignID = a.AdGroup.Campaign.ID,
           CampaignName = a.AdGroup.Campaign.Name,
           CampaignBudget = a.AdGroup.Campaign.DailyBudget

       })
    .GroupBy(adgroup => adgroup.ID)
    .Select(adgroup => new {
        ID = adgroup.Key,
        Name = adgroup.FirstOrDefault().Name,
        Spent = adgroup.Sum(q =>  q.Spent),
        CampaignID = adgroup.FirstOrDefault().CampaignID,
        CampaignName = adgroup.FirstOrDefault().CampaignName,
        CampaignBudget = adgroup.FirstOrDefault().CampaignBudget,
    })
    .GroupBy(q => q.CampaignID)
    .Select(campaigngroup => new {
      CampaignID = campaigngroup.Key,
      DailyBudget = campaigngroup.FirstOrDefault().CampaignBudget,
      Spent = campaigngroup.Sum(q => q.Spent),
      Ads = campaigngroup.GroupBy(q => q.ID).Select(adgroup => new {
        ID = adgroup.Key,
        Name  = adgroup.FirstOrDefault().Name,
        Spent = adgroup.FirstOrDefault().Spent
    })
    })

Results

正如您在屏幕截图中的结果中看到的那样正常,但是当我查看生成SQL查询时,我得到了402 lines of SQL code。怎么会这样?有什么我可以做的来增强代码

1 个答案:

答案 0 :(得分:0)

我唯一注意到的是,在最后一个GroupBy中,您不会聚合,而只会显示Key和第一个值。我想你也可以Select q.Idq.Nameq.Spent

因为你展示了两个级别的聚合(两次GroupBy),所以两个Spent s就足够了。