How to select a row having a column with min value - oracle

I am using oracle database and spring ibatis.
I have a query which will return two results from that i need to get a record which has minimum value on a column.
In Oracle i do that using below query:
SELECT *
FROM ANUMBER$ROOT ROOT
WHERE ROOT.ROOT_NUMBER=1546305
AND ROOT.MOL_WEIGHT = (SELECT MIN(MOL_WEIGHT)
FROM ANUMBER$ROOT
WHERE ROOT_NUMBER=1546305);
I have converted this query to like below in spring ibatis
SELECT *
FROM ANUMBER$ROOT ROOT
WHEREe ROOT.ROOT_NUMBER= #value#
AND ROOT.MOL_WEIGHT = (SELECT MIN(MOL_WEIGHT)
FROM ANUMBER$ROOT
WHERE ROOT_NUMBER= #value#);
But this throws me below error:
**log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly. Exception in
thread "main" org.springframework.jdbc.UncategorizedSQLException:
SqlMapClient operation; uncategorized SQLException for SQL []; SQL
state [null]; error code [0];
--- The error occurred in abbott/gprd/compoundInfo/dao/ibatis/LibraCompoundInformationLookup.xml.
--- The error occurred while preparing the mapped statement for execution.
--- Check the selectCompoundInfoByRootNumber.
--- Check the SQL statement.
--- Cause: java.util.NoSuchElementException; nested exception is com.ibatis.common.jdbc.exception.NestedSQLException:
--- The error occurred in abbott/gprd/compoundInfo/dao/ibatis/LibraCompoundInformationLookup.xml.
--- The error occurred while preparing the mapped statement for execution.
--- Check the selectCompoundInfoByRootNumber.
--- Check the SQL statement.
--- Cause: java.util.NoSuchElementException Caused by: com.ibatis.common.jdbc.exception.NestedSQLException:
--- The error occurred in abbott/gprd/compoundInfo/dao/ibatis/LibraCompoundInformationLookup.xml.
--- The error occurred while preparing the mapped statement for execution.
--- Check the selectCompoundInfoByRootNumber.
--- Check the SQL statement.
--- Cause: java.util.NoSuchElementException at com.ibatis.sqlmap.engine.mapping.statement.GeneralStatement.executeQueryWithCallback(GeneralStatement.java:188)
at
com.ibatis.sqlmap.engine.mapping.statement.GeneralStatement.executeQueryForObject(GeneralStatement.java:104)
at
com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.queryForObject(SqlMapExecutorDelegate.java:566)
at
com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.queryForObject(SqlMapExecutorDelegate.java:541)
at
com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl.queryForObject(SqlMapSessionImpl.java:106)
at
org.springframework.orm.ibatis.SqlMapClientTemplate$1.doInSqlMapClient(SqlMapClientTemplate.java:243)
at
org.springframework.orm.ibatis.SqlMapClientTemplate.execute(SqlMapClientTemplate.java:193)
at
org.springframework.orm.ibatis.SqlMapClientTemplate.queryForObject(SqlMapClientTemplate.java:241)
at
abbott.gprd.compoundInfo.dao.ibatis.CompoundInformationDao.getCompoundInformationForRootNumber(CompoundInformationDao.java:66)
at
abbott.gprd.compoundInfo.dao.ibatis.CompoundInformationDao.main(CompoundInformationDao.java:183)
Caused by: java.util.NoSuchElementException at
java.util.StringTokenizer.nextToken(StringTokenizer.java:332) at
com.ibatis.sqlmap.engine.mapping.sql.simple.SimpleDynamicSql.processDynamicElements(SimpleDynamicSql.java:90)
at
com.ibatis.sqlmap.engine.mapping.sql.simple.SimpleDynamicSql.getSql(SimpleDynamicSql.java:45)
at
com.ibatis.sqlmap.engine.mapping.statement.GeneralStatement.executeQueryWithCallback(GeneralStatement.java:168)
... 9 more ERROR: JDWP Unable to get JNI 1.2 environment,
jvm->GetEnv() return code = -2 JDWP exit error
AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:820]**
Can anyone please help me in converting this query from oracle to spring ibatis?

Too long for a comment:
You can find the row(s) with the minimum value for a given column using the RANK (or DENSE_RANK) analytic function (and this does not need the extra correlated query):
SELECT *
FROM (
SELECT root.*,
RANK() OVER ( ORDER BY MOL_WEIGHT ) AS rnk
FROM ANUMBER$ROOT ROOT
WHERE ROOT_NUMBER=1546305
)
WHERE rnk = 1;

Related

Oracle SQL Error occurred in XML processing for a query

Hi I am trying to run this query but getting this error
Query 1
select OWNER,table_name,
to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) as count
from all_tables
Runs fine
Query 2 - Included additional columns (sample_size, last_analyzed)
select OWNER,table_name,
to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) as count,
sample_size, last_analyzed
from all_tables
Error - ?
ORA-19202: Error occurred in XML processing
ORA-00933: SQL command not properly ended
ORA-06512: at "SYS.DBMS_XMLGEN", line 176
ORA-06512: at line 1
19202. 00000 - "Error occurred in XML processing%s"
*Cause: An error occurred when processing the XML function
*Action: Check the given error message and fix the appropriate problem
Query 2 - Issue what could be the issue ? - Explanation and resolution

HQL throws ArrayList cannot be cast to org.apache.hadoop.io.Text

I have a query which fails when reducing, the error which is thrown is:
Error: Error while processing statement: FAILED: Execution Error, return code 2 from org.apache.hadoop.hive.ql.exec.mr.MapRedTask (state=08S01,code=2)
However, when going deeper into the YARN logs, I was able to find this:
Error: java.lang.RuntimeException: org.apache.hadoop.hive.ql.metadata.HiveException: Hive Runtime Error while processing row (tag=0) {"key":{"reducesinkkey0":"2020-05-05","reducesinkkey1":10039,"reducesinkkey2":103,"reducesinkkey3":"2020-05-05","reducesinkkey4":10039,"reducesinkkey5":103},"value":{"_col0":103,"_col1":["1","2"]}} at org.apache.hadoop.hive.ql.exec.mr.ExecReducer.reduce(ExecReducer.java:265) at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:444) at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:392) at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:164) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:422) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1920) at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158) Caused by: org.apache.hadoop.hive.ql.metadata.HiveException: Hive Runtime Error while processing row (tag=0) {"key":{"reducesinkkey0":"2020-05-05","reducesinkkey1":10039,"reducesinkkey2":103,"reducesinkkey3":"2020-05-05","reducesinkkey4":10039,"reducesinkkey5":103},"value":{"_col0":103,"_col1":["1","2"]}} at org.apache.hadoop.hive.ql.exec.mr.ExecReducer.reduce(ExecReducer.java:253) ... 7 more Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to org.apache.hadoop.io.Text
The most relevant part being:
java.util.ArrayList cannot be cast to org.apache.hadoop.io.Text
This is the query which I'm executing (FYI: this is a subquery within a bigger query):
SELECT
yyyy_mm_dd,
h_id,
MAX(CASE WHEN rn=1 THEN prov_id ELSE NULL END) OVER (partition by yyyy_mm_dd, h_id) as primary_prov,
collect_set(api) OVER (partition by yyyy_mm_dd, h_id, p_id) prov_id_api, --re-assemple array to include all elements from multiple initial arrays if there are different arrays per prov_id
prov_id
FROM(
SELECT --get "primary prov" (first element in ascending array))
yyyy_mm_dd,
h_id,
prov_id,
api,
ROW_NUMBER() OVER(PARTITION BY yyyy_mm_dd, h_id ORDER BY api) rn
FROM(
SELECT --explode array to get data at row level
t.yyyy_mm_dd,
t.h_id,
prov_id,
collect_set(--array of integers, use set to remove duplicates
CASE
WHEN e.apis_xml_element = 'res' THEN 1
WHEN e.apis_xml_element = 'av' THEN 2
...
...
ELSE e.apis_xml_element
END) as api
FROM
mytable t
LATERAL VIEW EXPLODE(apis_xml) e AS apis_xml_element
WHERE
yyyy_mm_dd = "2020-05-05"
AND t.apis_xml IS NOT NULL
GROUP BY
1,2,3
)s
)s
I have further narrowed the issue down to the top level select, as the inner select works fine by itself, which makes me believe the issue is happening here specifically:
collect_set(api) OVER (partition by yyyy_mm_dd, h_id, prov_id) prov_id_api
However, I'm unsure how to solve it. At the most inner select, apis_xml is an array<string> which holds strings such as 'res' and 'av' up until a point. Then integers are used. Hence the case statement to align these.
Strangely, if I run this via Spark i.e. spark.sql=(above_query), it works. However, on beeline via HQL, the job gets killed.
Remove collect_set in the inner query, because it already produces array, upper collect_set should receive scalars. Also remove group by in the inner query, because without collect_set there is no aggregation any more. You can use DISTINCT if you need to remove duplicates

Is there any replacement for ROWNUM in Oracle?

I have JPA Native queries to an Oracle database. The only way I know to limit results is using 'rownum' in Oracle, but for some reason, query parser of a jar driver I have to use does not recognize it.
Caused by: java.sql.SQLException: An exception occurred when executing the following query: "/* dynamic native SQL query */ SELECT * from SFDC_ACCOUNT A where SBSC_TYP = ? and rownum <= ?". Cause: Invalid column name 'rownum'. On line 1, column 90. [parser-2900650]
com.compositesw.cdms.services.parser.ParserException: Invalid column name 'rownum'. On line 1, column 90. [parser-2900650]
How can I get rid of that?
ANSI Standard would be something like the following
SELECT *
FROM (
SELECT
T.*,
ROW_NUMBER() OVER (PARTITION BY T.COLUMN ORDER BY T.COLUMN) ROWNUM_REPLACE
FROM TABLE T
)
WHERE
1=1
AND ROWNUM_REPLACE < 100
or you could also use the following:
SELECT * FROM TABLE T
ORDER BY T.COLUMN
OFFSET 0 ROWS
FETCH NEXT 100 ROWS ONLY;

java.sql.SQLException: ORA-01000: maximum open cursors exceeded. While generating jasper report

While generating report through jasper we are getting exception error as ...
Error filling print... net.sf.jasperreports.engine.JRException: Error executing SQL statement for : risk
net.sf.jasperreports.engine.JRRuntimeException: net.sf.jasperreports.engine.JRException: Error executing SQL statement for : risk
at net.sf.jasperreports.engine.fill.JRFillSubreport.prepare(JRFillSubreport.java:729)
Caused by: java.sql.SQLException: ORA-01000: maximum open cursors exceeded
How to resolve this?
Сonnect to the database and check the open_cursors limits:
select value from v$parameter where name='open_cursors'
So we list the top 20 sessions which are currently opening most cursors:
select * from ( select ss.value, sn.name, ss.sid from v$sesstat ss, v$statname sn where ss.statistic# = sn.statistic# and sn.name like '%opened cursors current%' order by value desc) where rownum < 21;
The solution is to increase the no. of the open_cursors parameter as :
alter system set open_cursors=400 scope=both

Oracle java exception when trying to use NVL()

I have the following SQL statement in Oracle that is giving me some headache. I am trying to return an empty geometry if the value held in the Oracle table is null however it simply fails with the following error:
The Error
*
ORA-29532: Java call terminated by uncaught Java exception:
java.lang.NullPointerException ORA-06512: at "MDSYS.SDO_UTIL", line
2421 ORA-06512: at "MDSYS.SDO_UTIL", line 2443 ORA-06512: at
"MDSYS.SDO_GEOMETRY", line 36
*
The Code
select CLUSTER_ID,
NUM_POINTS,
FEATURE_PK,
A.CELL_CENTROID.SDO_POINT.X,
A.CELL_CENTROID.SDO_POINT.Y,
A.CLUSTER_CENTROID.SDO_POINT.X,
A.CLUSTER_CENTROID.SDO_POINT.Y,
TO_CHAR (A.CLUSTER_EXTENT.GET_WKT ()),
TO_CHAR (A.CELL_GEOM.GET_WKT ()),
A.CLUSTER_EXTENT.SDO_SRID,
TPHS_PHASE_ID
from (SELECT CLUSTER_ID,
NUM_POINTS,
FEATURE_PK,
SDO_CS.transform (CLUSTER_CENTROID, 4326) cluster_centroid,
SDO_CS.TRANSFORM(NVL(CLUSTER_EXTENT, MDSYS.SDO_GEOMETRY(2001,4326 ,MDSYS.SDO_POINT_TYPE(NULL,NULL,NULL),NULL,NULL)),4326) CLUSTER_EXTENT ,
SDO_CS.transform (CELL_CENTROID, 4326) cell_centroid, CELL_GEOM FROM
V_CLUSTER_1000M) a
LEFT JOIN RWOL_TMA_ROADWORKS
ON a.FEATURE_PK = RWOL_TMA_ROADWORKS.TPHS_PHASE_ID
where sdo_filter( A.CELL_GEOM, SDO_CS.transform(mdsys.sdo_geometry(2003,4326, NULL, mdsys.sdo_elem_info_array(1,1003,3),mdsys.sdo_ordinate_array(-25.43623984375,44.257784519021, 21.62918984375, 60.752403080295)),81989)) = 'TRUE'
Anybody got any idea what is going wrong here? I am no Oracle dev so any help is appreciated as well as an explanation.
The problem here was caused by the line
TO_CHAR (A.CLUSTER_EXTENT.GET_WKT ()),
This line is attempting to get a well known text item from the returned column and because we do not supply a valid one it is failing. Strange error really.

Resources