complex sql query with jpa jpql

Go To StackoverFlow.com

0

I use JPA2 for the dao layer.

Suppose i have a table as follows (just a sample):

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

according to the give tables, (actually more complex than this), how can i get the result like this

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

NB: the status also must be distinguished. also the hours column is not existed in the db, the column is start_time and end_time

so anyone can have some good idea for that? I can' group by any column, because it will mix result.

thanks for that.

2012-04-05 02:08
by ttt


0

Try this:

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
2012-04-05 02:19
by Michael Rice
thanks for your help. it looks great.

however, if starttimestamp and endtimestamp column replace the hours, are there any good method - ttt 2012-04-05 02:26

hi Michael, if there is no hours column in the table, only start and end timestamp, how can I calculate the right hours - ttt 2012-04-05 02:53
Not sure if JPA supports something like MySQL's TIMESTAMPDIFF. If it does replace SUM(hours) with SUM(TIMESTAMPDIFF(HOUR,start,end - Michael Rice 2012-04-05 04:29
If your tables are generated from JPA Entities, try using @Temporal(TemporalType.TIMESTAMP), if your tables are manually created, change column data type to TIMESTAMP, not DATE (depends on vendor) - JMelnik 2012-04-05 06:07
Ads