LINQ2SQL和NHibernate,按计算列分组

时间:2015-11-20 20:06:16

标签: c# sql-server nhibernate linq-to-sql

在SQL Server数据库中,我有一个包含日志条目的表 - timestampdescription

我需要按指定的时间间隔(30分钟)获取日志。

E.g:

01.01.2015 00:00 - 100
01.01.2015 00:30 - 200
01.01.2015 01:00 - 2

依旧......

我有什么:

var logs = session.Query<Log>;

//... other operations on logs queryable

var intervalInMinutes = 30;
var logsFrequency = logs
    .GroupBy(l => new
    {
        Year = l.LogTimestamp.Year,
        Month = l.LogTimestamp.Month,
        Day = l.LogTimestamp.Day,
        Hour = l.LogTimestamp.Hour,
        Minute = (l.LogTimestamp.Minute / intervalInMinutes) * intervalInMinutes,
    })
    .Select(g => new LogsOccurence()
    {
        StartingDatetime = new DateTime(g.Key.Year, g.Key.Month, g.Key.Day, g.Key.Hour, g.Key.Minute, 0),
        Frequency = g.Count()
    })
    .ToList();

以下查询失败:

  

类型的例外&#39; NHibernate.Exceptions.GenericADOException&#39;发生在NHibernate.dll但未在用户代码中处理

     

其他信息:无法执行查询

     

内部异常:列&#39; dbo.Log.LogTimestamp&#39;在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

生成的select语句是:

select 
    datepart(year, Log0_.LogTimestamp) as col_0_0_
    , datepart(month, Log0_.LogTimestamp) as col_1_0_
    , datepart(day, Log0_.LogTimestamp) as col_2_0_
    , datepart(hour, Log0_.LogTimestamp) as col_3_0_
    , datepart(minute, Log0_.LogTimestamp) as col_4_0_
    , cast(count(*) as INT) as col_5_0_
from 
    dbo.[Log] Log0_
group by 
    datepart(year, Log0_.LogTimestamp)
    , datepart(month, Log0_.LogTimestamp)
    , datepart(day, Log0_.LogTimestamp)
    , datepart(hour, Log0_.LogTimestamp)
    , datepart(minute, Log0_.LogTimestamp)/@p0*@p1
Name:p1 - Value:30  Name:p2 - Value:30
  1. groupby子句

    中的运算符优先级/顺序错误
    datepart(minute, Log0_.LogTimestamp) / @p0 * @p1
    
  2. 分钟的选择部分与分组的部分不同 - 选择失败

  3. 我的Linq有什么问题,以及如何写出正确的?

    我正在使用NHibernate build 4.0.4.GA。

0 个答案:

没有答案