5

我真的可以使用一些关于如何将此 sql 查询带到 NHibernate QueryOver 的指导。我的尝试是使用 Linq,因为我对 Linq 更熟悉一些。我们正在进行的项目正在使用 QueryOver,所以现在最好还是保持这条路线。

工作 SQL 查询:将 DateTime 舍入到 1 分钟并正确分组/排序/计数...

select dateadd(minute,(datediff(minute,0,dateTimeColumn)/1)*1,0), COUNT(*)
from PartData
group by dateadd(minute,(datediff(minute,0,dateTimeColumn)/1)*1,0)
order by dateadd(minute,(datediff(minute,0,dateTimeColumn)/1)*1,0)

返回预期结果:

2012-08-31 00:00:00.000, 3
2012-08-31 00:01:00.000, 4
2012-08-31 00:02:00.000, 3
2012-08-31 00:03:00.000, 3
2012-08-31 00:04:00.000, 4
2012-08-31 00:05:00.000, 3
2012-08-31 00:06:00.000, 3
2012-08-31 00:07:00.000, 4
2012-08-31 00:08:00.000, 3

编辑

我越来越近了……

private IQueryOver<entities.PartData, entities.PartData> PartPerHourQuery(ISession session)
{
    return session.QueryOver<entities.PartData>()
        .Select(
            Projections.Alias(
                Projections.GroupProperty(
                    Projections.SqlFunction(
                        new SQLFunctionTemplate(NHibernateUtil.DateTime, "DateAdd(mm,1,Date)"),
                        NHibernateUtil.DateTime, _partsDate))
                , "Date"),
            Projections.Alias(Projections.RowCount(), "Count"))
                .TransformUsing(Transformers.AliasToBean<entities.PartsPerHour>());
}

产生以下 SQL:

SELECT DateAdd(mm,1,dateTimeColumn), count(*)
FROM [PartData] 
GROUP BY DateAdd(mm,1,dateTimeColumn)

只需要弄清楚如何在那里获取 datediff :)

4

1 回答 1

8

凭借毅力的力量,我成功地赢得了这场战斗。这是我对上述 SQL 查询的 QueryOver ......我相信我已经在这个 NHibernate 事情上转了个弯 :)

非常感谢任何有关改进或替代方法以重现预期结果的建议。

private IQueryOver<entities.PartData, entities.PartData> PartPerHourQuery(ISession session)
{
    return session.QueryOver<entities.PartData>()
        .Select(
            Projections.Alias(
                Projections.GroupProperty(
                    Projections.SqlFunction(
                        new SQLFunctionTemplate(NHibernateUtil.DateTime, "DateAdd(minute," +
                                                                         new SQLFunctionTemplate(
                                                                             NHibernateUtil.DateTime,
                                                                             "(DateDiff(minute, 0, Date)/1)*1") +
                                                                         ",0)"),
                        NHibernateUtil.DateTime, _partsDate))
                , "Date"),
            Projections.Alias(Projections.RowCount(), "Count"))
        .TransformUsing(Transformers.AliasToBean<entities.PartsPerHour>());
}
于 2012-09-02T19:39:36.450 回答