MyBatis Error with less than equal to and greater than equal symbols - sql

I am working a fix to one sql query to include a where clause with less than equal and greater than equal in a case statement but whenever I try to run I get the same error message saying the <= token was not valid. I have tried the symbols as both html code and wrapped in CDATA brackets both give the same error. The mybatis queue is below.
WHERE A.WDATE BETWEEN #{fdate} AND #{tdate}
AND A.FAC LIKE #{fac}
<if test = 'good != "%"'>
AND SUBSTR(A.ITDSC,21,4) NOT LIKE #{good}
</if>
<if test = 'size != ""'>
AND CASE WHEN #{size} = '16' THEN SUBSTR(A.ITDSC,13,2) <= '16' ELSE SUBSTR(A.ITDSC,13,2) >= '17' END
</if>

Escaping <= and >= with <= and >= looks OK and works for me.
But that part of the where-clause
AND
CASE
WHEN #{size} = '16' THEN SUBSTR(A.ITDSC,13,2) <= '16'
ELSE SUBSTR(A.ITDSC,13,2) >= '17'
END
looks suspicious.
In DB2 the CASE has to be part of an expression, e.g.
WHERE xyz >= CASE WHEN ... THEN ... END
or
WHERE
(CASE WHEN ... THEN ... ELSE ... END) >= xyz
See case-expressions for more info and examples.

Try this, maybe work;)
WHERE A.WDATE BETWEEN #{fdate} AND #{tdate}
AND A.FAC LIKE #{fac}
<if test = 'good != "%"'>
AND SUBSTR(A.ITDSC,21,4) NOT LIKE #{good}
</if>
<if test = 'size != ""'>
AND ((#{size} = '16' AND SUBSTR(A.ITDSC,13,2) <= '16') OR SUBSTR(A.ITDSC,13,2) >= '17')
</if>

I was able to solve the problem by using two IF statements for size one for size =='16' and the other for size=='17'

Related

CASE Expression within WHERE clause for different date fields

I'm trying to include a case expression within a where clause, to show all records depending on two forms of criteria. I'm getting lots of syntax errors with the below and wondering what I'm missing?
...
AND
CASE WHEN (TypeName = 'Category1' or TypeName = 'Category2') THEN
Headers.HeaderDate < DATEADD(dd,1,#ReportDate)
ELSE
Headers.TimeStamp < DATEADD(dd,1,#ReportDate)
END
Case is an expression not a statement and as such returns a value, not a condition, so you want
AND CASE WHEN (TypeName = 'Category1' OR TypeName = 'Category2')
THEN Headers.HeaderDate ELSE Headers.TimeStamp END < DATEADD(dd,1,#ReportDate)
There is a way to do it without using a case expression
and (
(Typename in ('Category1','Category2') and Headers.HeaderDate < DATEADD(dd,1,#ReportDate)
or (Typename not in ('Category1','Category2') and Headers.TimeStamp < DATEADD(dd,1,#ReportDate)
)
If Typename can be null you should also keep it in mind.

Unable to Correct Oracle Error ORA-00905 Missing Keyword in SQL

I've been grinding on this small snippet of simple code for a day and can't find the issue causing the error. As the title states, I am getting error ORA-00905 Missing Keyword when trying to execute the following code:
SELECT DISTINCT DM.DESCRIPTION AS "AGENCY",
DM.DEPT_NO AS "DEPT NO",
CASE
WHEN VMP.RESERVE_DT IS NULL THEN
NULL
ELSE
VMP.RESERVE_DT
END AS "RESV_DT",
CASE
WHEN VMP.EST_PICKUP_DT IS NULL THEN
NULL
ELSE
VMP.EST_PICKUP_DT
END AS "EST_PKUP_DT",
CASE
WHEN VMP.EST_RETURN_DT IS NULL THEN
NULL
ELSE
VMP.EST_RETURN_DT
END AS "EST_RETN_DT",
VMP.EMP_NAME AS "EMPL_NAME",
VMP.UNIT_NO AS "UNIT_NUMBER",
VMP.RENTAL_CLASS_DESCRIPTION AS "RENT_CLS",
VMP.MP_TICKET_NO AS "MP_TKT_NO"
FROM DEPT_MAIN DM
INNER JOIN VIEW_MPOOL VMP ON VMP.DEPT_ID = DM.DEPT_ID
WHERE CASE
WHEN VMP.EST_PICKUP_DT IS NULL THEN
NULL
ELSE
TRUNC(VMP.EST_PICKUP_DT) = TRUNC(SYSDATE)
END
GROUP BY DM.DESCRIPTION,
DM.DEPT_NO,
CASE
WHEN VMP.RESERVE_DT IS NULL THEN
NULL
ELSE
VMP.RESERVE_DT
END,
CASE
WHEN VMP.EST_PICKUP_DT IS NULL THEN
NULL
ELSE
VMP.EST_PICKUP_DT
END,
CASE
WHEN VMP.EST_RETURN_DT IS NULL THEN
NULL
ELSE
VMP.EST_RETURN_DT
END,
VMP.EMP_NAME,
VMP.UNIT_NO,
VMP.RENTAL_CLASS_DESCRIPTION,
VMP.MP_TICKET_NO
ORDER BY CASE
WHEN VMP.EST_PICKUP_DT IS NULL THEN
NULL
ELSE
VMP.EST_PICKUP_DT
END ASC
The basis of this code was generated through an adhoc reporting program and was originally fully-qualified. I stripped out the extraneous quotation marks and assigned table aliases to clean it up. Though I hoped these efforts would help me find the issue, I am unable to find the cause. Thank you for your consideration.
Try to replace this :
WHERE
CASE
WHEN VMP.EST_PICKUP_DT IS NULL THEN NULL
ELSE TRUNC(VMP.EST_PICKUP_DT) = TRUNC(SYSDATE)
END
With :
WHERE
CASE
WHEN VMP.EST_PICKUP_DT IS NULL THEN NULL
ELSE TRUNC(VMP.EST_PICKUP_DT)
END
= TRUNC(SYSDATE)
Please note that this whole expression (and others similar in the query) could be simplified as as :
WHERE
TRUNC(VMP.EST_PICKUP_DT) = TRUNC(SYSDATE)
When VMP.EST_PICKUP_DT is NULL, TRUNC will return NULL, which will not be equal to TRUNC(SYSDATE).
Here:
WHERE
CASE
WHEN VMP.EST_PICKUP_DT IS NULL
THEN NULL
ELSE TRUNC(VMP.EST_PICKUP_DT) = TRUNC(SYSDATE)
END
The END is after a comparison and the case is not being compared against a value.
Switch it like:
WHERE
CASE
WHEN VMP.EST_PICKUP_DT IS NULL
THEN NULL
ELSE TRUNC(VMP.EST_PICKUP_DT)
END = TRUNC(SYSDATE)
Which as horse says, can just be simplified as
WHERE TRUNC(VMP.EST_PICKUP_DT) = TRUNC(SYSDATE)
since a NULL value on VMP.EST_PICKUP_DT will never match TRUNC(SYSDATE).
can't find the issue causing the error
Although I suppose that #EzLo and #a_horse_with_no_name maybe already found error in this case, I can propose a general procedure in debugging such queries.
Step 1: Debug your JOIN- and WHERE- predicates
Comment everything in your SELECT-statement, leave only JOINs, substitute fields with * or constant expression.
E.g.
SELECT 1
-- DISTINCT DM.DESCRIPTION AS "AGENCY",
-- DM.DEPT_NO AS "DEPT NO",
-- CASE
-- ....
-- VMP.RENTAL_CLASS_DESCRIPTION AS "RENT_CLS",
-- VMP.MP_TICKET_NO AS "MP_TKT_NO"
FROM DEPT_MAIN DM
INNER JOIN VIEW_MPOOL VMP ON VMP.DEPT_ID = DM.DEPT_ID
WHERE CASE
WHEN VMP.EST_PICKUP_DT IS NULL THEN
NULL
ELSE
TRUNC(VMP.EST_PICKUP_DT) = TRUNC(SYSDATE)
END
-- GROUP BY DM.DESCRIPTION,
-- ....
-- ORDER BY ..
In case of multiple complex predicates - uncomment one predicate at a time.
Step 2: Debug your GROUP BYs and HAVINGs
Uncomment GROUP BY section and edit fields section of your query.
If you have complex groupby's - uncomment by one field at time.
Start from simplest to complex
SELECT
DM.DESCRIPTION
,DM.DEPT_NO
-- ...
FROM DEPT_MAIN DM
INNER JOIN VIEW_MPOOL VMP ON VMP.DEPT_ID = DM.DEPT_ID
WHERE CASE
WHEN VMP.EST_PICKUP_DT IS NULL THEN
NULL
ELSE
TRUNC(VMP.EST_PICKUP_DT) = TRUNC(SYSDATE)
END
GROUP BY DM.DESCRIPTION
,DM.DEPT_NO
Copy-paste your GROUP BYs into SELECT fields section.
Step 3: Debug you aggregates, field transformation and renames
Now you have correct SELECT-query but probably not in the shape you want.
Step 4: Debug ORDER BYs
You have correct shape and in last step you need to ORDER BY your data.
If you have decent editor/IDE you can find source of error in 5-10 minutes even in cases of complex queries (and even RDBMS engine bugs)
P.S.
It's better to note which version of RDBMS you are using.

SQL Query Error with CASE Statement?

I'm attempting to run this query using Simba's ODBC SFDC driver but the log shows me an error near the case statement. I'm not totally convinced its an error with the CASE statement but I don't see where my error is. Someone please help!!!!
SELECT
Account_Group__c,
Hospital_Sales_Teammate__c,
Name,
StageName,
CloseDate,
Yr_Credited__c,
Probability,
Census__c,
Credit__c,
Related_VSA__c,
AB_Hospital_Relationship_Type__c,
CASE
WHEN Age_In_Stage__c >0 and Age_In_Stage__c <= 30 THEN '<30'
WHEN Age_In_Stage__c >30 and Age_In_Stage__c <= 60 THEN '31-60'
WHEN Age_In_Stage__c >60 and Age_In_Stage__c <= 90 THEN '61-90'
ELSE '>90' END AS Age_Bucket,
CASE
WHEN (Type = "Existing Business - Renewal" OR Type = 'Existing Business - Amendment')
AND (Account_HHV_Segment__c='A' OR Account_HHV_Segment__c='B')
AND AB_Hospital_Relationship_Type__c<>'N/A'
AND (RecordType='012300000000PWuAAM'
OR RecordType='01250000000DcJkAAK'
OR RecordType='01250000000DpV4AAK'
OR RecordType='01250000000Dxd7AAC'
OR RecordType='01250000000DoFPAA0'
OR RecordType='01250000000DuuEAAS') THEN 'Hosp'
WHEN Name LIKE '%AB Hospital Loss%' THEN 'Hosp'
ELSE '' END AS Hospital_Eligible,
CASE
WHEN RecordType='01250000000DpV4AAK'
AND Type LIKE '%Acquisition%'
THEN 'Acq'
ELSE '' END AS Acquisition_Eligible,
CASE
WHEN RecordType='01250000000Dxd7AAC'
AND (Business_Unit__c="Full Conversion" OR Business_Unit__c="Partial Conversion")
THEN 'BGC'
ELSE '' END AS Conversion_Eligible,
CASE
WHEN RecordType='01250000000DuuEAAS'
AND Type_of_Agreement__c ="MDA" OR Type_of_Agreement__c ="Joinder" OR Type_of_Agreement__c ="JV"
THEN 'Incr Doc'
ELSE '' END AS Incr_Doc_Eligible
FROM
Opportunity
WHERE
Eligible__c<>'No'
AND NOT Name LIKE '%test%'
AND NOT Name LIKE '%Test%'
AND NOT Name LIKE '%TEST%'
ORDER BY
Account_Group__c ASC
Business_Unit__c="Full Conversion" (and other places as well): You are using double quotes instead of single quotes (as you do in the rest of the query). I bet that's the problem...
Also, this is a case expression, not a statement.
Why are you using double quotes?
(Type = "Existing Business - Renewal" OR Type = 'Existing Business - Amendment')
You should change it to
(Type = 'Existing Business - Renewal' OR Type = 'Existing Business - Amendment')

how to use > = condition in sql case statement?

I am trying to place a >= condition in statement, but it is not allowing this condition.
case
when ct.CRS_CAREER_LVL_CD = 'G' then 'Graduate '
when ct.CRS_CAREER_LVL_CD = 'L' then 'Law '
when convert(int, left(ct.CRS_CATLG_NO, 4) > = 99 then 'Upper Division'
else 'Lower Division'
end as courseLevelName
Is there any other way to do this ?
when convert(int,left(ct.CRS_CATLG_NO,4)
^ ^ ^ ^
OPEN OPEN CLOSE CLOSE ?
Guessing the problem is that the left 4 characters of are not always integers, if you're using SQL Server 2012 or newer you can use TRY_CONVERT():
case when ct.CRS_CAREER_LVL_CD = 'G' then 'Graduate '
when ct.CRS_CAREER_LVL_CD = 'L' then 'Law '
when TRY_CONVERT(int,left(ct.CRS_CATLG_NO,4)) > = 99 then 'Upper Division'
else 'Lower Division'
end as courseLevelName
Edit: Looks like you were missing a closing ), if that wasn't a typo then that's likely the issue, if still getting an error then might be non-INT.

SPARK SQL - case when then

I'm new to SPARK-SQL. Is there an equivalent to "CASE WHEN 'CONDITION' THEN 0 ELSE 1 END" in SPARK SQL ?
select case when 1=1 then 1 else 0 end from table
Thanks
Sridhar
Before Spark 1.2.0
The supported syntax (which I just tried out on Spark 1.0.2) seems to be
SELECT IF(1=1, 1, 0) FROM table
This recent thread http://apache-spark-user-list.1001560.n3.nabble.com/Supported-SQL-syntax-in-Spark-SQL-td9538.html links to the SQL parser source, which may or may not help depending on your comfort with Scala. At the very least the list of keywords starting (at time of writing) on line 70 should help.
Here's the direct link to the source for convenience: https://github.com/apache/spark/blob/master/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/SqlParser.scala.
Update for Spark 1.2.0 and beyond
As of Spark 1.2.0, the more traditional syntax is supported, in response to SPARK-3813: search for "CASE WHEN" in the test source. For example:
SELECT CASE WHEN key = 1 THEN 1 ELSE 2 END FROM testData
Update for most recent place to figure out syntax from the SQL Parser
The parser source can now be found here.
Update for more complex examples
In response to a question below, the modern syntax supports complex Boolean conditions.
SELECT
CASE WHEN id = 1 OR id = 2 THEN "OneOrTwo" ELSE "NotOneOrTwo" END AS IdRedux
FROM customer
You can involve multiple columns in the condition.
SELECT
CASE WHEN id = 1 OR state = 'MA'
THEN "OneOrMA"
ELSE "NotOneOrMA" END AS IdRedux
FROM customer
You can also nest CASE WHEN THEN expression.
SELECT
CASE WHEN id = 1
THEN "OneOrMA"
ELSE
CASE WHEN state = 'MA' THEN "OneOrMA" ELSE "NotOneOrMA" END
END AS IdRedux
FROM customer
For Spark 2.+
Spark when function
From documentation:
Evaluates a list of conditions and returns one of multiple possible result expressions. If otherwise is not defined at the end, null is returned for unmatched conditions.
// Example: encoding gender string column into integer.
// Scala:
people.select(when(col("gender") === "male", 0)
.when(col("gender") === "female", 1)
.otherwise(2))
// Java:
people.select(when(col("gender").equalTo("male"), 0)
.when(col("gender").equalTo("female"), 1)
.otherwise(2))
This syntax worked for me in Databricks:
select
org,
patient_id,
case
when (age is null) then 'Not Available'
when (age < 15) then 'Less than 15'
when (age >= 15 and age < 25) then '15 to 25'
when (age >= 25 and age < 35) then '25 to 35'
when (age >= 35 and age < 45) then '35 to 45'
when (age >= 45) then '45 and Older'
end as age_range
from demo
The decode() function analog of Oracle SQL for SQL Spark can be implemented as follows:
​ case
​ ​ ​ when exp1 in ('a','b','c')
​ ​ ​ ​ then element_at(map('a','A','b','B','c','C'), exp1)
​ ​ ​ else exp1
​ ​ end
Based on my current production code, this works
val identifierDF =
tempIdentifierDF.select(tempIdentifierDF("t_item_account_id"),
when(tempIdentifierDF("h_description").contains(tempIdentifierDF("t_cusip")),100)
.when(tempIdentifierDF("h_description").contains(tempIdentifierDF("t_ticker")),100)
.when(tempIdentifierDF("h_description").contains(tempIdentifierDF("t_isin")),100)
.when(tempIdentifierDF("h_description").contains(tempIdentifierDF("t_sedol")),100)
.when(tempIdentifierDF("h_description").contains(tempIdentifierDF("t_valoren")),100)
.otherwise(0)
.alias("identifier_in_description_score")
)
Spark DataFrame API (Python version) also enable to do next query:
df.selectExpr('time', \
'CASE WHEN (time > 1) THAN time * 1.1 ELSE time END AS updated_time')