Jooq query issue with case - java

I wrote this mysql query and tried to convert it to JOOQ query but not succeeded , this is mysql query
SELECT `P`.`phone_number`, `A`.`emp_no`,
SUM(CASE WHEN VCG.vid IN (
SELECT gv.vid FROM `grvas` gv JOIN gprs gr ON gr.id=gv.grid
WHERE gr.id=G.id AND gv.stdate < '2011-08-15' AND gv.enddate > '2011-09-14')
THEN VCG.amount END) AS allow,
... etc...
How can i convert this query to JOOQ query ?
Thanks,

This:
SUM(
CASE
WHEN VCG.vid IN (
SELECT gv.vid
FROM `grvas` gv
JOIN gprs gr ON gr.id=gv.grid
WHERE gr.id=G.id
AND gv.stdate < '2011-08-15'
AND gv.enddate > '2011-09-14'
)
THEN VCG.amount
END
) AS allow
Would translate to something like this:
import static org.jooq.impl.DSL.*;
// And then
sum(
decode()
.when(VCG.VID.in(
select(GRVAS.VID)
.from(GRVAS)
.join(GPRS).on(GPRS.ID.eq(GRVAS.GRID))
.where(GPRS.ID.eq(G.ID))
.and(GRVAS.STDATE.lt(Date.valueOf("2011-08-15")))
.and(GRVAS.ENDDATE.gt(Date.valueOf("2011-09-14")))
)), VCG.AMOUNT)
).as("allow")
The above example omitted table aliasing in the subquery of the IN predicate, to simplify things. Of course, you could go on and alias all those tables as well.

I couldn't find a proper way to convert above sql to JOOQ but i used
String sql="SELECT `P`.`phone_number`, `A`.`emp_no`,
SUM(CASE WHEN VCG.vid IN (
SELECT gv.vid FROM `grvas` gv JOIN gprs gr ON gr.id=gv.grid
WHERE gr.id=G.id AND gv.stdate < '2011-08-15' AND gv.enddate > '2011-09-14')
THEN VCG.amount END) AS allow,
... etc... " ;
Result<Record> res = f.fetch(sql);
This work fine
Thanks

Related

Best way for text extraction (classification) over a SQL query in java

I have several SQL queries like this (about 10.000):
SELECT (COLUMN BODY)
FROM (TABLES BODY)
WHERE...
The where part is optional.
I need to extract the "COLUMN BODY" AND "TABLES BODY" from the query, but those are dynamic (I have found SQL functions and subqueries a lot)
Think as getting an vector with the divided query or something like that:
String result = [SELECT, "COLUMN BODY", FROM, "TABLES BODY", WHERE, ... ]
The purpose, I'm working in an "SQL translator" and I need extract those parts from that dynamic queries. I have tried string splitting and other but the result is so frustrating, so I'm looking for an alternative to achieve that. I'm working on a java project.
What is the best way to get that?
Edit
Those are examples of the queries:
SELECT COMPANIA, ANO, TIPO_COBRO, CODIGO, DESCRIPCION FROM SF_DESCRIPCIONES_ESTAND
SELECT AUT_FAMILIARES.COMPANIA, AUT_FAMILIARES.DCTO_EMPLEADO, AUT_FAMILIARES.SUCURSAL_EMPLEADO, AUT_FAMILIARES.IDENTIFICACION, AUT_FAMILIARES.SUCURSAL, AUT_FAMILIARES.CONSECUTIVO, AUT_FAMILIARES.DCTO_IDENTIDAD, AUT_FAMILIARES.PARENTESCO, AUT_FAMILIARES.NOMBRE, AUT_FAMILIARES.FECHANCTO, AUT_FAMILIARES.SEXO, AUT_FAMILIARES.OBSERVACIONES, AUT_FAMILIARES.POLIZA, AUT_FAMILIARES.SALUD, AUT_FAMILIARES.PORCENTAJE, AUT_FAMILIARES.OCUPACION, AUT_FAMILIARES.TELEFONO, AUT_FAMILIARES.POS, AUT_FAMILIARES.AUXILIO_EDUCATIVO, AUT_FAMILIARES.APELLIDO1, AUT_FAMILIARES.APELLIDO2, AUT_FAMILIARES.DIRECCION, AUT_FAMILIARES.ESTADO_ACTUAL, AUT_FAMILIARES.DCTO_IDENTIDAD_A, AUT_FAMILIARES.PARENTESCO_A, AUT_FAMILIARES.NOMBRE_A, AUT_FAMILIARES.SEXO_A, AUT_FAMILIARES.OBSERVACIONES_A, AUT_FAMILIARES.POLIZA_A, AUT_FAMILIARES.SALUD_A, AUT_FAMILIARES.PORCENTAJE_A, AUT_FAMILIARES.OCUPACION_A, AUT_FAMILIARES.TELEFONO_A, AUT_FAMILIARES.POS_A, AUT_FAMILIARES.AUXILIO_EDUCATIVO_A, AUT_FAMILIARES.APELLIDO1_A, AUT_FAMILIARES.APELLIDO2_A, AUT_FAMILIARES.DIRECCION_A, AUT_FAMILIARES.ESTADO_ACTUAL_A, AUT_FAMILIARES.ESTADO, AUT_FAMILIARES.DESTINATARIO, AUT_FAMILIARES.SUCURSAL_DESTINATARIO, AUT_FAMILIARES.TIPO_SOLICITUD, AUT_FAMILIARES.FECHA_APROBACION, AUT_FAMILIARES.ENVIADO, AUT_FAMILIARES.ACTUALIZADO, AUT_FAMILIARES.RUTA, AUT_FAMILIARES.CREATED_BY, AUT_FAMILIARES.DATE_CREATED, AUT_FAMILIARES.MODIFIED_BY, AUT_FAMILIARES.DATE_MODIFIED, AUT_FAMILIARES.N_IDENTIFICACION, AUT_FAMILIARES.EDAD, AUT_FAMILIARES.EDAD_A FROM AUT_FAMILIARES
SELECT DISTINCT CARGOS.ID_DE_CARGO, CARGOS.NOMBRE_DEL_CARGO FROM EV_EVALUADOR_EVALUADO EVAL INNER JOIN CARGOS ON EVAL.COMPANIA = CARGOS.COMPANIA AND EVAL.CARGO_EVALUADO = CARGOS.ID_DE_CARGO WHERE EVAL.COMPANIA = :COMPANIA AND EVAL.CLASE_EVALUACION = :CLASEEVALUACION AND CARGOS.ID_DE_CARGO >= :CODIGO ORDER BY CARGOS.ID_DE_CARGO
SELECT ROWNUM CODIGO, DECODE (ROWNUM, 1,'Activo',2,'Pensionado',3,'Retirado',4,'Suspensión Preventiva',5,'Activarlo para Ajustes Liquidación',6,'Comisión',7,'Encargos')NOMBRE FROM DUAL CONNECT BY ROWNUM < 8
SELECT * FROM ( SELECT A.*, ROWNUM RNUM FROM(SELECT * FROM (SELECT INVENTARIO.CODIGOELEMENTO, INVENTARIO.NOMBRELARGO FROM INVENTARIO WHERE INVENTARIO.COMPANIA = :COMPANIA AND INVENTARIO.TIPO NOT IN ('C') ORDER BY INVENTARIO.COMPANIA, INVENTARIO.CODIGOELEMENTO) WHERE (CASE WHEN CODIGOELEMENTO IS NULL THEN ' ' ELSE UPPER(CODIGOELEMENTO) END) LIKE UPPER(:CODIGOELEMENTO || '%') AND (CASE WHEN NOMBRELARGO IS NULL THEN ' ' ELSE UPPER(NOMBRELARGO) END) LIKE UPPER( '%' || :NOMBRELARGO || '%') ) A WHERE ROWNUM <= (:PAGINICIO + :PAGTAMANIO)) WHERE RNUM > :PAGINICIO

Convert sql view query to hql

I'm new in Java, so please help if you can.
I need to populate Jtable and I'm doing it with this code:
SELECT r.id AS roomID, r.type, r.no_of_rooms, r.no_of_rooms -
COALESCE(t.bookedRooms,0) AS available_rooms FROM room AS r LEFT JOIN (
SELECT room_id, SUM(total_rooms) AS bookedRooms FROM bookings WHERE
`start` < '2017-02-10' AND `ends` > '2017-02-09' GROUP BY room_id ) AS t
ON r.id = t.room_id WHERE r.no_of_rooms - COALESCE(t.bookedRooms,0) > 0
and it works like this.
But how can I do this with Hibernate and how to do mapping?
Thanks in advance!

Postgresql and Java passing one value and using it in multiple places without cross join

I have a query I am writing in postgresql. I am calling this from a java jdbc library using a prepared statement. I have a date field that I want to pass in to see if any of the relating tables have updated since I last checked. However I don't know how to have the date fill multiple spots. Here is what works.
WHERE p.last_updated_time > '2015-02-06 11:21:32.064'
OR p.p_id IN (
SELECT DISTINCT con.p_id
FROM enriched.p_con con
WHERE con.last_updated_time > '2015-02-06 11:21:32.064'
)
OR p.p_id IN (
SELECT DISTINCT pi.p_id
FROM enriched.p_ident pi
WHERE pi.last_updated_time > '2015-02-06 11:21:32.064'
)
OR p.p_id IN (
SELECT DISTINCT pp.p_id
FROM enriched.p_p pp
WHERE pp.last_updated_time > '2015-02-06 11:21:32.064'
)
OR p.p_id IN (
SELECT DISTINCT prov.p_id
FROM enriched.p_prov prov
WHERE prov.last_updated_time > '2015-02-06 11:21:32.064'
)
However when I change it to use the prepared statement to the following I get an error.
WHERE p.last_updated_time > ?
OR p.p_id IN (
SELECT DISTINCT con.p_id
FROM enriched.p_con con
WHERE con.last_updated_time > ?
)
OR p.p_id IN (
SELECT DISTINCT pi.p_id
FROM enriched.p_ident pi
WHERE pi.last_updated_time > ?
)
OR p.p_id IN (
SELECT DISTINCT pp.p_id
FROM enriched.p_p pp
WHERE pp.last_updated_time > ?
)
OR p.p_id IN (
SELECT DISTINCT prov.p_id
FROM enriched.p_prov prov
WHERE prov.last_updated_time > ?
)
I tried using a cross join which works but takes my query time from 45 seconds to several days.
CROSS JOIN (SELECT TO_DATE(?, 'YYYY-MM-DD HH:MI:SS.MS') last_crawl_date) ld
Any thoughts? This seems like a simple problem to fix but I just can't seem to see it.
You have 5 ? in your prepared statement SQL, so you'll need to set the date five times.
statement.setDate(1, yourDate);
statement.setDate(2, yourDate);
statement.setDate(3, yourDate);
statement.setDate(4, yourDate);
statement.setDate(5, yourDate);

Maximo setWhere() query to get distinct results?

I'm trying to do this SQL query:
select distinct wonum from invreserve where location='01' order by wonum;
How can this be converted to a setWhere() query? I've tried:
invreserveSet.setWhere("(1 = 1) and wonum in (select distinct wonum from invreserve where location='01')");
work with something like this:
select invreserveid from invreserve where invreserveid in (select invreserveid from invreserve invr2 where location like '%B%'
and invreserveid = (select max(invreserveid) from invreserve invr3 where invr3.location = invr2.location and invr3.wonum = invr2.wonum))
;
so your where clause would be the same as this ones except your location wildcard would be different.

Hibernate #Formula is not supporting query contains 'CAST() as int' function

Following is the one of property of ExecutionHistory class, which value is fetched from
#Formula using JPA/Hibernate from exectution_history table,
#Formula("(SELECT SUM(dividend) || '/' || SUM(divisor) " +
"FROM (SELECT CAST(substr(sr.result, 1, position('/' in sr.result)-1 ) AS int) AS dividend ," +
"CAST(substr(sr.result, position('/' in sr.result)+1 ) AS int) AS divisor " +
"FROM suite_results as sr WHERE sr.execution_history=id) AS division)")
private String result;
When I tried to get instance of ExecutionHistory class, I found that above formula query
is converted by JPA/Hibernate like this:
select executionh0_.id as id7_1_, executionh0_.execution_plan as execution3_7_1_, executionh0_.start_time as start2_7_1_,
(SELECT SUM(sr.duration) FROM suite_results as sr WHERE sr.execution_history=executionh0_.id) as formula0_1_,
(SELECT SUM(executionh0_.dividend) || '/' || SUM(executionh0_.divisor) FROM
(SELECT CAST(substr(sr.result, 1, position('/' in sr.result)-1 ) AS executionh0_.int) AS executionh0_.dividend ,
CAST(substr(sr.result, position('/' in sr.result)+1 ) AS executionh0_.int) AS executionh0_.divisor
FROM suite_results as sr WHERE sr.execution_history=executionh0_.id) AS executionh0_.division) as
formula1_1_, executionp1_.id as id6_0_, executionp1_.build_number as
build2_6_0_, executionp1_.name as name6_0_, executionp1_.owner as owner6_0_, executionp1_.sut as sut6_0_,
executionp1_.wait_for_page_to_load as wait6_6_0_ from execution_history executionh0_
left outer join execution_plans executionp1_ on executionh0_.execution_plan=executionp1_.id where executionh0_.id=?
So the problem is that, here formula query contains "CAST() AS int", but during query conversion by Hibernate, it puts unnecessary table reference and execute it as "CAST() AS executionh0_.int" so it giving sql grammer exeception while execution.
I've no idea about how to avoid this problem, Can anybody help me in this?
Thanks.
It's an old question, but I'll post an answer anyway.
If you are using a SQL Server database, you can add double quotes around the type you are casting.
Something like this:
#Formula("CAST(FLOOR(CAST( dat_criacao AS \"float\")) AS \"datetime\")")
Don't know which database you're using, but in SQL Server you should use CONVERT rather than CAST in you Hibernate queries.

Categories