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

时间:2013-10-01 05:15:30

标签: c# entity-framework-5

我在campaignscampaign stats之间存在一对多的关系。对于一天的广告系列,广告系列统计信息项最多只能包含一个条目。

从13/20/13开始 - DateTime.Now获取campaigns,其中没有相关的campaign stat,但我还想获得缺少统计信息的实际日期从

我想显示例如campaign namestat 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 个答案:

答案 0 :(得分:1)

递归时很难看,但是:

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