Is it possible to run such a a query like this below in JPA/Hibernate?
select v.country,
v.site,
SUM(case when s.id = 1 then 1 else 0 end) as Total_SuspectedViolations,
SUM(case when s.id = 2 then 1 else 0 end) as Total_ConfirmedViolations,
SUM(case when s.id = 3 then 1 else 0 end) as Total_ConfirmedNoViolations,
SUM(case when s.id = 4 then 1 else 0 end) as Total_NotDetermined,
COUNT(*) Total
from violations v
inner join status s
on v.status_id = s.id
group by v.country, v.site
or
select v.country,
v.site,
SUM(case when v.status_id = 1 then 1 else 0 end) as Total_SuspectedViolations,
SUM(case when v.status_id = 2 then 1 else 0 end) as Total_ConfirmedViolations,
SUM(case when v.status_id = 3 then 1 else 0 end) as Total_ConfirmedNoViolations,
SUM(case when v.status_id = 4 then 1 else 0 end) as Total_NotDetermined,
COUNT(*) Total
from violations v
group by v.country, v.site
This works in Oracle DB but when I am using JPA/Hibernate I am getting:
ERROR [PARSER] line 1:311: unexpected token: total
ERROR [PARSER] line 1:375: unexpected token: ON
I am asking because I need to implement some simple statistics based on data in one table "Violations"
Below is my idea:
I need to join two tables and count occurrences some values from second table to achieve effect like statistics table which will have columns:
Result Table:
- country varchar(20),
- site varchar(20),
- suspected_violation long,
- confirmed_violation long,
- confirmed_no_violation long,
- not_determined long,
- total long
My Result Table needs to have first two columns (contry and site) comes from first table "Violations" and next 5 columns which will contain numbers (count) of occurrences status_id in "Violations" in each of possible values of id from Status table.
So, I have existing two tables: Violations and Status.
Violations:
- id long,
- country varchar(20),
- site varchar(20),
- status_id long, <-- this is the id of status in Status table.
- ... other columns not important in this case
Status:
- id long,
- status long Column "status" have values (1-4) which are mapped to string values: Suspected Violation (1), Confirmed Violation (2), Confirmed No Violation (3), Not Determined (4)
In result of my join is to have table which should contain columns:
- from Violations table: "Country" and "Site"
- from Status table: "Suspected Violation", "Confirmed Violation", "Confirmed No Violation", "Not Determined", "Total" (where this columns are counters of occurrences in Violation table).
UPDATE: As far as I know now there is no need to use join, query can be run on one table only.
Can you suggest me what is the proper way to do that in JPA/Hibernate?