使用jpa jpql进行复杂的sql查询

时间:2012-04-05 02:08:02

标签: java sql hibernate jpa jpql

我使用JPA2作为dao图层。

假设我有一张如下表格(只是一个样本):

emp_name     week     approver_name  status   hours
emp1       2010-01-02    app1          a        2
emp1       2010-01-02    app1          a        2
emp1       2010-01-02    app2          b        3
emp1       2010-01-09    app1          b        2
emp1       2010-01-09    app2          a        7
emp2       2010-01-02    app1          b        5
emp2       2010-01-02    app2          a        9
emp2       2010-01-02    app1          a        3
emp2       2010-01-09    app2          a        4
emp2       2010-01-09    app2          b        7
emp2       2010-01-09    app1          a        3
emp2       2010-01-09    app1          a        2

根据给定表,(实际上比这更复杂),我怎样才能得到像这样的结果

emp_name     week     approver_name    status  hours (add hours together)
emp1      2010-01-02      app1          a        4
emp1      2010-01-02      app2          b        3
emp1      2010-01-09      app1          b        2
emp1      2010-01-09      app2          a        7
emp2      2010-01-02      app1          b        5
emp2      2010-01-02      app1          a        3
emp2      2010-01-02      app2          a        9
emp2      2010-01-09      app1          a        5
emp2      2010-01-09      app2          a        4
emp2      2010-01-09      app2          b        7

注意:必须区分状态。数据库中也不存在hours列,该列是start_time和end_time

所以任何人都可以有一些好主意吗?我可以按任意列进行分组,因为它会混合结果。

谢谢你。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT emp_name, week, approver_name, status, SUM(hours)
FROM MyTable
GROUP BY emp_name, week, approver_name, status
ORDER BY emp_name, week, approver_name, status