How can I use CASE expression with SUM function in SQL? - sql

I have an Oracle SQL query that I need to select certain deduction codes and provide a predetermined amount if based on the premium amount for deduction code 91B. These are hard coded values that I need to summarize.
SELECT SUM(DECODE(DEDCD,'91A',AL_AMOUNT,0)) MED91A,
SUM(CASE WHEN DEDCD = '91B' THEN
DECODE(AL_AMOUNT, 23.54,7.85,
40.62,8.31,
43.85,8.31,
56.77,8.31,
AL_AMOUNT)) MED91B
FROM PS_AL_CHK_DED
WHERE WEEK_NBR = 6
AND TO_CHAR(CHECK_DT, 'YYYY')=TO_CHAR(SYSDATE, 'YYYY')
The SUM(DECODE ..) statement used to summarize values where dedcd = '91A' works fine. When I add the part to summarize values where dedcd = '91B' it produces a 'Missing Keyword' error after the decode statement. I'm trying to streamline the query in order to produce the results I need for these two deduction codes because the full query takes entirely too long to run.
Oracle Sql Developer 4.0.2.15

You must complete the case expression syntax with an END keyword.
Do it like this:
CASE WHEN DEDCD = '91B' THEN
DECODE(AL_AMOUNT, 23.54,7.85,
40.62,8.31,
43.85,8.31,
56.77,8.31,
AL_AMOUNT)
END
A basic case expression looks like:
CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
See the documentation for more details.

Related

MariaDB Case statement

I have the following SQL-Code in a Mariadb-Database:
(1)
select Labornummer, Matrix, FaktorGW, FaktorAW
from gc_Faktoren
I need the following result:
If Matrix='AW' => I need the field "FaktorAW"
else => I need the field "FaktorGW"
is it possible to formulate Statement (1) with a "case statement"?
Of course, this is possible.
Basically you can do this:
SELECT labornummer, matrix, faktoraw, faktorgw,
CASE WHEN matrix = 'AW' THEN faktoraw
ELSE faktorgw END AS factor
FROM gc_faktoren;
You have to take care if this is really exactly what you want, e.g. this will not check lower/upper case. See the working example:
db<>fiddle
Try
select Labornummer, Matrix, FaktorGW, FaktorAW,
CASE
WHEN Matrix = 'AW' THEN FaktorAW ELSE FaktorGW END as New_Field
from gc_Faktor

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 ;

SQL Developer: invalid identifier error

This is the part of my query that has error:
, case when dsi.distributor_id in
('ALBQA','ASGLA','ASGNY','ASGR1','ASGSF','BIKU9','COAUU','CSWHP','DPIB1','DPID9',
'DPISP','DPISQ','EAS3X','GEP79','GRG8V','NACY7','NOSYK','ORGK7','PETR1','TOP0U',
'UNFIA','UNFIL','UNFIQ','UNFIS','UNMQ9','KOSI8','KEHEN','CSNYC','ALBQA','ALC6Y','BAM7D','BIKU9','CLCE0','COAUU','CSWHT','EAS3X','FOUXU','GEP79',
'GRG8V','HED9Q','LAOJD','MCLFS','NOSYK','ORGK7','UNMQ9','OMAH1'
)
then 'Distributor'
else 'Direct'
end as is_direct
, SUM(dsi.cost) AS tot_cost
, SUM(CASE WHEN is_direct = 'Direct' THEN dsi.cost ELSE 0 END ) AS Direct_cost
It says that is_direct is an invalid column but I already indicated it above. Therefore, I was wondering if you could help me find where I went wrong.
Columns defined in your query cannot be used in other places in your query, whether it is in other columns, or WHERE clauses, etc.
I would suggest either placing these calculations into subqueries, or using WITH AS.

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.

How to select if a row exists in HQL

EDIT: Specifically talking about querying against no table. Yes I can use exists, but I'd have to do
select case when exists (blah) then 1 else 0 end as conditionTrue
from ARealTableReturningMultipleRows
In T-SQL I can do:
select case when exists(blah) then 1 else 0 end as conditionTrue
In Oracle I can do:
select case when exists(blah) then 1 else 0 end as conditionTrue from DUAL
How can I achieve the same thing in HQL?
select count() seems like the second-best alternative, but I don't want to have to process every row in the table if I don't need to.
Short answer: I believe it's NOT possible.
My reasoning:
According to Where can I find a list of all HQL keywords? Hibernate project doesn't publish HQL grammar on their website, it's available in the Hibernate full distribution as a .g ANTLR file though.
I don't have much experience with .g files from ANTLR, but you can find this in the file (hibernate-distribution-3.6.1.Final/project/core/src/main/antlr/hql.g):
selectFrom!
: (s:selectClause)? (f:fromClause)? {
// If there was no FROM clause and this is a filter query, create a from clause. Otherwise, throw
// an exception because non-filter queries must have a FROM clause.
if (#f == null) {
if (filter) {
#f = #([FROM,"{filter-implied FROM}"]);
}
else
throw new SemanticException("FROM expected (non-filter queries must contain a FROM clause)");
}
which clearly states there are some HQL queries having no FROM clause, but that's acceptable if that's a filter query. Now again, I am not an expert in HQL/Hibernate, but I believe a filter query is not a full query but something you define using session.createFilter (see How do I turn item ordering HQL into a filter query?), so that makes me think there's no way to omit the FROM clause.
I'm use fake table with one row for example MyDual.
select case when exists(blah) then 1 else 0 end as conditionTrue from MyDual
According to http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-expressions it looks like they support both case and exists statements.