If operator in groovy sql select statement - sql

I would like to use the if operator in the select statement, using an executeQuery command.
Something like:
def tmpRec = BankStatement.executeQuery("select SUM(IF(operation='CREDIT',cashAmount,-1*cashAmount)) from BankStatement group by portfolio,currency,code")
go
but the IF operator doesn't work.
thank you

Although I do not know Groovy SQL, in most DBMS the CASE statement is used as a conditional statement. Perhaps the following will work:
def tmpRec = BankStatement.executeQuery("select SUM(CASE WHEN operation='CREDIT' THEN cashAmount ELSE (-1*cashAmount) END) from BankStatement group by portfolio,currency,code")

Related

SQL case query with DISTINCT in cakephp3 ORM

I am trying to build a case query with distinct count in cakephp 3.
This is the query in SQL:
select COUNT(distinct CASE WHEN type = 'abc' THEN app_num END) as "count_abc",COUNT(distinct CASE WHEN type = 'xyz' THEN app_num END) as "count_xyz" from table;
Currently, I got this far:
$query = $this->find();
$abc_case = $query->newExpr()->addCase($query->newExpr()->add(['type' => 'abc']),' app_num','string');
$xyz_case = $query->newExpr()->addCase($query->newExpr()->add(['type' => 'xyz']),'app_num','string');
$query->select([
"count_abc" => $query->func()->count($abc_case),
"count_xyz" => $query->func()->count($xyz_case),
]);
But I can't apply distinct in this code.
Using keywords in functions has been a problem for quite some time, see for example this issue ticket: https://github.com/cakephp/cakephp/issues/10454.
This has been somewhat improved in https://github.com/cakephp/cakephp/pull/11410, so that it's now possible to (mis)use a function expression for DISTINCT as kind of a workaround, ie generate code like DISTINCT(expression), which works because the parentheses are being ignored, so to speak, as DISTINCT is not a function!
I'm not sure if this works because the SQL specifications explicitly allow parentheses to be used like that (also acting as a whitespace substitute), or because it's a side-effect, so maybe check that out before relying on it!
That being said, you can use the workaround from the linked PR until real aggregate function keyword support is being added, ie do something like this:
"count_abc" => $query->func()->count(
$query->func()->DISTINCT([$abc_case])
)
This would generate SQL similar to:
(COUNT(DISTINCT(CASE WHEN ... END)))

SQL query using if else

My SQL code looks like this:
SELECT
Scores.PupilId, Scores.BoysName, Scores.FormGroup,
IF (Scores.FormGroup = "10SB", "Great", "ok")
FROM
Scores
I get this message
no such function: if: SELECT Scores.PupilId, Scores.BoysName, Scores.FormGroup,
if(Scores.FormGroup="10SB","Great","ok")
FROM Scores
This is flat file database
Can anyone please help me understand why I am getting a message?
The correct ANSI-standard conditional expression in SQL is the case expression:
SELECT Scores.PupilId, Scores.BoysName, Scores.FormGroup,
(CASE WHEN Scores.FormGroup = '10SB' THEN 'Great' ELSE 'ok' END)
FROM Scores ;

ORA-00933 using case/when inside a select

I'm trying to write this code into the toad, but it throws an ORA-00933 (SQL command not properly ended), just at the first WHEN.
I don't know exactly what happens. I've tried to follow the ORACLE docs, but with no success. Any help?
I let you the code written with toad.
select template.seq_temp, rules.fec_desde_serv, rules.seq_rec, rules.seq_agencia, rules.SEQ_TTOO, rules.COD_INTERFACE, pais.COD_PAIS, rules.cod_idioma
from re_t_vp_voucher_template template, re_t_vp_voucher_rules rules, re_t_vp_voucher_rules_pais pais,
case &tipser
when 'TRF' then re_t_vp_voucher_rules_trf trf
when 'ACC' then re_t_vp_voucher_rules_acc acct
else re_t_vp_voucher_rules_otro otro
end
where template.seq_temp = rules.seq_temp
and RULES.SEQ_RULE = PAIS.SEQ_RULE
group by template.seq_temp, rules.fec_desde_serv, rules.seq_rec, rules.seq_agencia, rules.SEQ_TTOO, rules.COD_INTERFACE, pais.COD_PAIS, rules.cod_idioma
order by template.seq_temp, rules.fec_desde_serv;
You cannot use CASE construct in FROM clause.
So your SQL as highlighted below is incorrect.
from re_t_vp_voucher_template template, re_t_vp_voucher_rules rules, re_t_vp_voucher_rules_pais pais,
case &tipser
when 'TRF' then re_t_vp_voucher_rules_trf trf
when 'ACC' then re_t_vp_voucher_rules_acc acct
else re_t_vp_voucher_rules_otro otro
end
where template.seq_temp = rules.seq_temp
The reason is that, you are trying to use dynamic table names in SQL, which is NOT allowed. You can't use dynamic table names in SQL unless you write dynamic SQL statements (i.e. build up the statement as a string in PL/SQL and then execute it using EXECUTE IMMEDIATE or the DBMS_SQL package).
So rewrite the query to meet the SQL standards, or (ab)use dynamic sql.
CASE is an expression, which works like IF-THEN-ELSE logic, and Oracle
uses short-circuit evaluation. so, it always needs a comparison
expression. Which you cannot have in FROM clause.
Your where condition is wrong.:-
where template.seq_temp = rules.seq_temp
and RULES.SEQ_RULE = PAIS.SEQ_RULE
case &tipser
when 'TRF' then and rules.seq_rule = trf.seq_rule
when 'ACC' then and rules.seq_rule = acct.seq_rule
else and rules.seq_rule = otro.seq_rule
end
Try to remove the 'and' keywords from there.

Access to T-SQL query conversion - What to use in place of the IIf() function?

My query is as follows :
I have written in access can anyone pls help how can I convert it into sql query I am getting an error near IIF condition.
SELECT #NT_VAR_STEP_1_1.SYS_ID, #NT_VAR_STEP_1_1.NODE, #NT_VAR_STEP_1_1.TEMP_ID,
#NT_VAR_STEP_1_1.EQUIP_TYPE, #NT_VAR_STEP_1_1.EQ_ID,
#NT_VAR_STEP_1_1.VAR_ID, #NT_VAR_STEP_1_1.NODE AS VAR_SET,
#NT_VAR_STEP_1_1.VAR_NAME, IIf([#NT_VAR_STEP_1_1]![VAR_SUBSET]=‘SELF’,
[#NT_VAR_STEP_1_1]![NODE],[#NT_VAR_STEP_1_1]![VAR_SUBSET]) AS VAR_SUBSET,
IIf([#NT_VAR_STEP_1_1]![EQUIP_TYPE]=‘SOURCE’,’PARAMVAR’,’VAR’) AS CALC_VAR_TYPE,
#NT_VAR_STEP_1_1.VAR_DATA_TYPE AS DATA_TYPE, #NT_VAR_STEP_1_1.DOF,
#NT_VAR_STEP_1_1.RETAIN, #NT_VAR_STEP_1_1.COEFF_OBJECT,
#NT_VAR_STEP_1_1.COEFF_VAR_SET, #NT_VAR_STEP_1_1.COEFF_VAR_TYPE,
#NT_VAR_STEP_1_1.COEFF_VAR_SUBSET, #NT_VAR_STEP_1_1.COEFF_VAR_NAME,
#NT_VAR_STEP_1_1.OPERAND, #NT_VAR_STEP_1_1.SIGN,
#NT_VAR_STEP_1_1.VAR_TP_OFFSET, #NT_VAR_STEP_1_1.COEFF_TP_OFFSET,
#NT_VAR_STEP_1_1.COEFF_VAR_SUBTYE INTO #OT_VAR_STEP_1_1_1
FROM #NT_VAR_STEP_1_1
GROUP BY #NT_VAR_STEP_1_1.SYS_ID, #NT_VAR_STEP_1_1.TEMP_ID,
#NT_VAR_STEP_1_1.EQUIP_TYPE, #NT_VAR_STEP_1_1.EQ_ID,
#NT_VAR_STEP_1_1.VAR_ID, #NT_VAR_STEP_1_1.NODE,
#NT_VAR_STEP_1_1.VAR_NAME, IIf([#NT_VAR_STEP_1_1]![VAR_SUBSET]=‘SELF’,
[#NT_VAR_STEP_1_1]![NODE],[#NT_VAR_STEP_1_1]![VAR_SUBSET]),
IIf([#NT_VAR_STEP_1_1]![EQUIP_TYPE]=‘SOURCE’,’PARAMVAR’,’VAR’),
#NT_VAR_STEP_1_1.VAR_DATA_TYPE, #NT_VAR_STEP_1_1.DOF,
#NT_VAR_STEP_1_1.RETAIN, #NT_VAR_STEP_1_1.COEFF_OBJECT,
#NT_VAR_STEP_1_1.COEFF_VAR_SET, #NT_VAR_STEP_1_1.COEFF_VAR_TYPE,
#NT_VAR_STEP_1_1.COEFF_VAR_SUBSET, #NT_VAR_STEP_1_1.COEFF_VAR_NAME,
#NT_VAR_STEP_1_1.OPERAND, #NT_VAR_STEP_1_1.SIGN,
#NT_VAR_STEP_1_1.VAR_TP_OFFSET, #NT_VAR_STEP_1_1.COEFF_TP_OFFSET,
#NT_VAR_STEP_1_1.COEFF_VAR_SUBTYE, #NT_VAR_STEP_1_1.NODE
HAVING (((#NT_VAR_STEP_1_1.EQUIP_TYPE)<>‘COST_NODE’));
Convert this line:
IIf([#NT_VAR_STEP_1_1]![EQUIP_TYPE]=‘SOURCE’,’PARAMVAR’,’VAR’) AS CALC_VAR_TYPE
to this:
CASE WHEN [#NT_VAR_STEP_1_1].[EQUIP_TYPE]='SOURCE'
THEN 'PARAMVAR'
ELSE 'VAR'
END CALC_VAR_TYPE
And then use the same in your GROUP BY clause, but without the column alias:
CASE WHEN [#NT_VAR_STEP_1_1].[EQUIP_TYPE]='SOURCE'
THEN 'PARAMVAR'
ELSE 'VAR'
END
I will assume you're going to SQL Server (T-SQL). T-SQL does not support IIF, you will need to use CASE instead.

Using a CASE statement in HQL select

Is there any way to do the following in HQL:
SELECT
case when flag = true then SUM(col1) else SUM(col2)
FROM
myTable
I guess you can (3.6, 4.3) [inline edit] ...for where-clauses:
"Simple" case, case ... when ... then ... else ... end, and "searched" case, case when ... then ... else ... end
Apparently the ability to do this was added in 3.0.4, with the limitation that you cannot use sub-selects in the else clause.
See Hibernate-Forum: https://forum.hibernate.org/viewtopic.php?t=942197
Answer from Team (Gavin):
case is supported in the where clause, but not in the select clause in HB3.
And seen in JIRA with State "Unresolved".
Below you can find a working query (hibernate on postgresql) that uses 2 case statements to replace a boolean value with the corresponding textual representation.
SELECT
CASE ps.open WHEN true THEN 'OPEN'
else 'CLOSED' END,
CASE ps.full WHEN true THEN 'FULL'
else 'FREE' END,
ps.availableCapacity
FROM ParkingState as ps
I facing the same problem in HQL then I solved the following query is
select CONCAT(event.address1,', ', CASE WHEN event.address2 IS NULL THEN '' ELSE concat(event.address2,', ') END, event.city from EventDetail event where event.startDate>=:startDate and event.endDate<=:endDate;
We use hibernate HQL query extensively and I think finally there is a hackish way of doing such a thing :
Assuming we originally had a query of
i2.element.id = :someId
Then decided to expand this to be something like this:
((i.element.id = :someId and i2.element.id=:someId) or (i2.element.id = :someId))
But there was an issue where we want it to only lookup for this based on classType so a case statement:
(case when type(i)=Item then
((i.element.id = :someId and i2.element.id=:someId) or (i2.element.id = :someId))
else
i.element.id = :someId
end)
Above will not work you could make an easy version of above work by doing:
(case when type(i)=Item then
i2.element.id
else
i.element.id
end)=:elementId
But this does not actually do what we need it to do, we want it to do exact above query, so knowing you can assign a variable at the end of a case statement in there where bit of HQL:
(
(
(case when
type(r)=Item then
i.element.id
else
i.element.id end) = :elementId
and
(case when
type(r)=Item then
i2.element.id
else
i.element.id end) = :elementId
)
or
(case when
type(r)=Item then
i2.element.id
else
i.element.id end) = :elementId
)
I have managed to make the query now work based on case statement, sure it is a lot more long winded but actually does the same as the first instance
This is an example using a string comparison in the condition:
SELECT CASE f.type WHEN 'REMOVE'
THEN f.previousLocation
ELSE f.currentLocation
END
FROM FileOperation f