SQL从GROUP BY hibernate中删除arithmatic

时间:2013-10-17 15:44:00

标签: java sql hibernate

我目前有一个在SQL中运行良好的查询,但我需要它在Hibernate中运行。它查找时间窗口内2个字段的记录数。但是,快速谷歌搜索会告诉你,你不能在hibernate的GROUP BY子句中使用算术表达式。

我的表/ SQL:

CREATE TABLE T ( 
    Field_1 CHAR(4),
    Field_2 CHAR(4),
    Time_Stamp Date
);

--Populated

DECLARE @DATE1 DATE, @DATE2 DATE, @INTERVAL INT;
@DATE1 = TO_DATE('2013-01-01', 'yyyy-MM-dd');
@DATE2 = TO_DATE('2013-01-02', 'yyyy-MM-dd');
@INTERVAL = 15;

SELECT * FROM (
    SELECT COUNT(Field_1) as field1, 
        COUNT(Field_2) as field2, 
        FLOOR( TO_NUMBER( TO_CHAR( Time_Stamp, 'hhmi' ) ) / @INTERVAL ) as timeInterval
    FROM T
    WHERE Time_Stamp BETWEEN @DATE1 AND @DATE2
    GROUP BY FLOOR( TO_NUMBER( TO_CHAR( Time_Stamp, 'hhmi' ) ) / @INTERVAL )
) ORDER BY timeInterval ASC;

正如您所看到的,我可以删除ORDER BY,以便使用子查询在其中没有算术。是否可以在此实例中使用GROUP BY子句或其他一些方法执行类似的操作?

我已经在hibernate中编写了查询,并且可以在两者之间进行转换,我只需要查询的结构,因此算法在函数组之外,SQL语法就可以了。

1 个答案:

答案 0 :(得分:1)

在内部查询中执行计算,然后按其结果进行分组。

SELECT 
        COUNT(Field_1) as field1, 
        COUNT(Field_2) as field2,
        timeInterval
 FROM (
    SELECT 
        Field_1,
        Field_2,
        FLOOR( TO_NUMBER( TO_CHAR( Time_Stamp, 'hhmi' ) ) / @INTERVAL ) as timeInterval
    FROM T
    WHERE Time_Stamp BETWEEN @DATE1 AND @DATE2
) 
GROUP BY timeInterval
ORDER BY timeInterval ASC;