MariaDB Case statement - sql

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

Related

SQL Subquery to replace all values

I have a query which returns a bunch of different data, however I want to have it replace all the values upon a certain condition.
What I have written below kind of gives me the result I want but not really. It creates a new column instead of replacing the other one:
SELECT
CASE
WHEN T4.[U_DestType] = '6'
THEN (SELECT
'Company Limited' AS [ShipToCode]
)
END AS [ShipToCode],
T2.[ShipToCode],
T6.[StreetS],
T6.[StreetNoS],
T6.[CityS],
T6.[ZipCodeS],
T6.[CountryS],
T5.[LicTradNum],
T2.[CardCode],
T4.[Phone1],
T4.[E_Mail],
T4.[U_DestType],
CASE
WHEN T4.[Country] = 'GB'
THEN 'EN'
ELSE T4.[Country]
END AS [Country],
T4.[U_ShortName]
FROM[...]
The end goal is to replace all of the columns with some preset values instead of just ShipToCode as above.
I tried putting an EXIST subquery after FROM too but that didn't work either.
Is this possible? I'm probably missing something very obvious.
Many thanks!
You can use an ELSE in your CASE expression to combine the two "columns":
CASE
WHEN T4.[U_DestType] = '6'
THEN (SELECT
'Company Limited' AS [ShipToCode]
)
ELSE T2.[ShipToCode]
END AS [ShipToCode],
And by the way, you didn't need to use a Sub-Select. This would work just as well and is easier to read:
CASE
WHEN T4.[U_DestType] = '6' THEN 'Company Limited'
ELSE T2.[ShipToCode]
END AS [ShipToCode],

How can I use CASE expression with SUM function in 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.

Use CASE statement to test values in table 1, set values in table 2

I am new to SQL, so if you could include in answer correct syntax (for PostgreSQL) that will be great.
I have two tables
table 1 "geo_temp", with columns [geo_type1] [geo_type2]....[geo_type6] [geo_typeR];
table 2 "geo_summary", with column [geo].
Here what I want to do,
CASE
WHEN (geo_type1 NOTNULL) THEN (geo = geo_type1)
WHEN (geo_type2 NOTNULL) THEN (geo = geo_type2)
...
ELSE (geo = geo_typeR)
Your help is much appreciated. Thanks.
Use the coalesce() function:
geo = coalesce(geo1, geo2, ...,geoR)
coalesce() returns the first non-null value found in the list, which is what your intention is.
As an update statement:
update geo_summary set
geo = (select coalesce(geo1, geo2, ...,geoR)
from geo_temp
where geo_temp.id = geo_summary.id)
I am assuming you want to use this in a WHERE or ON Clause.
You could do something like...
geo =
CASE
WHEN (geo_type1 is NOT NULL) THEN geo_type1
WHEN (geo_type2 is NOT NULL) THEN geo_type2
...
ELSE geo_typeR
END

Alternative to relying on execution order of conditions in SQL 'where' clause

In languages such as JavaScript you can have 2 conditional statements and "protect" the second one with the first one. For instance:
if( scarryObject != null && scarryObject.scarryMethod() ) { ... }
// if scarryObject is null scarryMethod will not be called
I thought I would achieve the same in SQL like so:
where int_date > 19500101
and month(CONVERT(smalldatetime, ... int_date))
The problem here is that if int_date is some "bad" value like -1, 0, 1 the conversion will fail and the sp will stop with an error. I thought the first check int_date > 19500101 would get evaluated first and if false the second condition would be skipped.
It seems like it does not work like this... or? Is there any other way of doing this?
Thanks!
Your query is syntactically not correct, as the clausemonth(CONVERT.... is not a condition.
Let's assume you want to compare with a certain number, a possible way of expressing what you want would be
SELECT *
FROM myTable
WHERE case
when int_date > 19500101
then -1
else month(CONVERT(smalldatetime, ... int_date))
end = #YourMonth
You would 'protect' the evaluation of the 'month' and not the condition.
You could try splitting the query into two. Here is the concept:
SELECT *
FROM (
SELECT *
FROM myTable
WHERE int_date > 19500101
) t
WHERE month(CONVERT(smalldatetime, ... t.int_date))

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.