代码之家  ›  专栏  ›  技术社区  ›  The Muffin Man

如何查询按日期不存在的项目

  •  0
  • The Muffin Man  · 技术社区  · 12 年前

    我有一对多的关系 campaigns campaign stats 。一个市场活动统计项目在一天的数据库中最多可以有一个项目。

    所以从2013年9月20日开始- DateTime.Now 收到 活动 没有相关的 campaign stat ,但我也想得到统计数据丢失的实际日期

    例如,我想显示 campaign name , stat date (这是缺失的)。我很难想出一个解决方案,但我已经开始写这段代码了。

            var fromDate = new DateTime(2013, 9, 20);
            var toDate = DateTime.Now;
            var dates = Enumerable.Range(0, toDate.Subtract(fromDate).Days + 1)
                .Select(d => fromDate.AddDays(d));
    
            var a = from c in _db.Campaigns
                join s in _db.CampaignStats on c.Id equals s.CampaignId into s1
                from s in s1.DefaultIfEmpty()
                where s == null
                select new {c, s};
    

    样本输出为: (活动1有2013年9月20日和2013年9日22日的统计数据)

    `Campaign 1 9/21/2013`
    `Campaign 1 9/23/2013`
    `Campaign 1 9/24/2013`
    `...`
    

    编辑

    使用Bob的回答,我形成了这个LINQ查询:

               (from counts in
                    (from cal in _db.CalendarMonths
                     from c in _db.Campaigns
                     let statCount = (from s in _db.CampaignStats
                                      where s.CampaignId == c.Id
                                      where s.Date == cal.date
                                      group s by s.Id into s1
                                      select s1.Count()).FirstOrDefault()
                     select new
                            {
                                cal.date,
                                c.Id,
                                statCount
                            })
                where counts.statCount == 0
                select new
                       {
                           counts.Id,
                           counts.date,
                       });
    
    1 回复  |  直到 12 年前
        1
  •  1
  •   Bob.Langley    12 年前

    递归很难看,但是:

    SELECT
        counts.CalDate,
        counts.CampaignId,
    FROM
        (SELECT
             cal.[Date] as CalDate,
             c.CampaignId,
             (SELECT COUNT(*) FROM CampaignStats WHERE CampaignID = c.CampaignId AND StatDate = cal.[Date]) AS StatCount
        FROM 
        CalendarMonths cal, Campaigns c) counts
    WHERE
        counts.StatCount = 0