每个ID查找多个日期的有效方法

时间:2015-03-03 08:41:52

标签: c# sql-server linq

我试图查询我的MsSQL Express数据库,找到所有有多个日期关联的公司ID - 当我说多个日期时,我必须指出它们需要在不同的日期。

EG

ID    UkDate        CompanyId
1    01/01/2015      16
2    01/01/2015      16
3    03/01/2015      18
4    05/01/2015      19
5    06/01/2015      20
6    08/01/2015      20

在上面的示例中,仅返回ComapnyID为20的行,因为它多次出现且这些时间超过了日期(请注意,虽然companyId 16有多个条目,但两个条目的日期相同)。

我不确定如何使用Linq为此编写查询。我的对象已经IQueryable<T>但是,我不确定如何在不执行代码的情况下执行查询,然后“完成”#39;查询。

我不在Visual Studio附近,但代码会是(请原谅输入错误,这是来自内存)

//First, grab unique CompanyIds as this removes those who didn't visit multiple times
var uniqueIds = (from d in this._database.MyTable 
                 select companyId).Distinct(); 


//This is the problem because on each iteration I'm re-querying the database! 
foreach(var id in uniqueIds) 
{
    var result = (from d in this._database.MyTable.OrderBy(a=>a.UkDate)
                  where d.CompanyId==id
                  select d);
   //check for nulls  

   if (result.First(a=>a.UkDate.Day) != result.Last(a => a.UkDate.Day)                      
   {
         this.AllResultsList.AddRange(results);
   } 
}

虽然它没有错误,但我觉得代码是正确的 - 感觉就像是黑客而且效率低下但是这是我最好的努力。有没有办法可以减少我所做的数据库请求数量并实现相同的结果

4 个答案:

答案 0 :(得分:4)

这将是

的内容
 var results = myTable.GroupBy(x => x.CompanyID)
                .Where(g => g.GroupBy(g2 => g2.UkDate).Count()>1)
                .Select(g => g.Key);

实例(虽然使用LinqToObjects,但查询应该可以很好地对数据库起作用):http://rextester.com/FPHI53553

答案 1 :(得分:2)

var results = (from o in this._database.MyTable
                           group o by o.CompanyId into grouped
                           where (grouped.Max(s => s.UKDate) - grouped.Min(s => s.UKDate)).TotalDays > 0
                           select grouped.Key);

编辑(按OP)

最终结果:

var results = (from o in this._database.MyTable
                       group o by o.CompanyId into grouped
                       where (Convert.ToDateTime(grouped.Max(s => s.UKDate)) - Convert.ToDateTime(grouped.Min(s => s.UKDate))).TotalDays > 0
                       from l in myTable
                       where l.CompanyID == grouped.Key
                       select l).ToList();

答案 2 :(得分:1)

一个不同的版本:

var result = (from o in this._database.MyTable
              group o by o.CompanyId into grouped
              select new {
                            grouped.Key,
                            Count = grouped.Select(c => c.UkDate).Distinct().Count()
                         } into filter
                 where filter.Count > 1
                 join a in this._database.MyTable on filter.Key equals a.CompanyID
                 select new { a.CompanyID, a.UkDate}
             ).ToList();

答案 3 :(得分:0)

如果您想要公司ID和不同日期的计数,您也可以尝试这个:

from c in dataTable
group c by c.CompanyId into grouped
let count =  grouped.Select(x => x.UkDate).Distinct().Count() 
where count > 1
select new { CompanyId = grouped.Key, Count = count }