3

我们正在开发一个广告平台并编写一个负责投放广告的大查询,向消费者投放广告有几个标准,其中一个标准是广告系列每日预算,所以我们正在做的是分组by Individual Ads 以获取展示次数和消耗的成本,然后我们按 Campaign 分组,产生以下查询:

  (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
    })
    })

结果

正如您在屏幕截图的结果中看到的那样,它运行良好,但是当我检查生成 SQL 查询时,我得到了402行 SQL 代码。怎么可能?我能做些什么来增强代码吗

4

1 回答 1

0

我唯一注意到的是,最后GroupBy你不聚合,而只显示Key和第一个值。我想你也可以Select q.Id, q.Name, 和q.Spent那里。

GroupBy由于您显示了两个聚合级别(两次Spent),因此两个s 就足够了。

于 2012-10-10T20:39:47.083 回答