我正在尝试创建一个返回日期分组结果的Linq查询。所面临的挑战是如何将每天/每周/每月/每季度的分组取决于可列举的参数(周期性)。下面是我当前的Linq查询:
var TotalGroupedInvoices = from c in entidades.InvoicesView
group c by (periodo == periodicity.Daily) ? c.InvoiceDate.Date :
period == periodicity.Weekly? c.InvoiceDate.Date.AddDays(-(double)c.InvoiceDate.DayOfWeek) :
period == periodicity.Monthly? new DateTime(c.InvoiceDate.Year,c.InvoiceDate.Month ,1) :
period == periodicity.Quarterly? new DateTime(c.InvoiceDate.Year, c.InvoiceDate.Month - (c.InvoiceDate.Month % 3) +1, 1) :
period == periodicity.Anual ? new DateTime(c.InvoiceDate.Year, 1, 1) : inicio into Periods
select new
{
period = Periods.Key,
Total = Periodos.Sum(c => c.Total)
};为了澄清这一点,请看一下季度期间代码片段:
period == periodicity.Quarterly? new DateTime(c.InvoiceDate.Year, c.InvoiceDate.Month - (c.InvoiceDate.Month % 3) +1, 1)因此,对于进入第一季度的日期,如:2012年1月/12日、2012年1月/15日或2012年3月20日,我将所有这些日期归为一个季度的乞丐:1月/1/2012,因此这是预期的结果。
首先,我想知道查询的效率。你觉得这个怎么样?为了提高SQL Server的效率,在客户端上重新转换到日期周期,也许用整数转换周期会更好,但我不确定。
另一方面,每周工作分组的日期为每周的第一个星期日:
period == periodicity.Weekly? c.InvoiceDate.Date.AddDays(-(double)c.InvoiceDate.DayOfWeek)...but,这对我来说是不正确的,因为我来自西班牙,周一开始。我怎样才能安排每周的小组来考虑这个问题呢?
因此,总结如下:
这个Linq到SQL查询efficiency?
非常感谢!PD:对不起,我的英语水平。
发布于 2012-02-20 13:03:43
要回答第一部分,您并不真正希望将枚举值传递到数据库中,让它来决定使用哪个代码分支。您有所有的信息在本地作出决定。
Expression<Func<InvoicesView, DateTime>> groupingExpr = c => c.InvoiceDate.Date;
if (period == periodicity.Weekly)
{
groupingExpr = c => c.InvoiceDate.Date.AddDays(-(double)c.InvoiceDate.DayOfWeek);
}
else if (period == periodicity.Monthly)
{
groupingExpr = c => new DateTime(c.InvoiceDate.Year,c.InvoiceDate.Month ,1);
}
else if (period == periodicity.Quarterly)
{
groupingExpr = c => new DateTime(c.InvoiceDate.Year, c.InvoiceDate.Month - (c.InvoiceDate.Month % 3) +1, 1);
}
else if (period == periodicity.Anual
{
groupingExpr = c => new DateTime(c.InvoiceDate.Year, 1, 1);
}
var TotalGroupedInvoices = entidades.InvoicesView
.GroupBy(groupingExpr)
.Select(grouped => new {
period = grouped.Key,
Total = grouped.Sum(c => c.Total)
});以下是我所能做的将groupingExpr与查询理解语法相结合的最好方法:
var TotalGroupedInvoices = from grouped in entidades.InvoicesView.GroupBy(groupingExpr)
select new {
period = grouped.Key,
Total = grouped.Sum(c => c.Total)
};发布于 2012-02-20 12:53:15
要回答第二部分,你只需要做一些“日”算术。您可以内联或作为一个单独的函数(例如扩展方法)执行此操作:
public static DateTime FirstDayOfWeek (this DateTime date)
{
double offset = (date.DayOfWeek == DayOfWeek.Sunday) ? -6 : (DayOfWeek.Monday - date.DayOfWeek);
return date.AddDays(offset);
}那么在你的LINQ中:
period == periodicity.Weekly ? c.InvoiceDate.FirstDayOfWeek但是,考虑到您正在从SQL检索此函数,您可能只想查看其中的日期函数,例如DATEPART,并在查询中返回它们。
https://stackoverflow.com/questions/9360631
复制相似问题