How to fix SQL error SAP HANA while using aggregate function - sql

If I run this sql in SAP HANA, It generates the following error.
(SQL Editor) Could not execute 'WITH l1 AS( SELECT REMOTE_SOURCE_NAME,OWNER,NAME,MAX(START_TIME) START_TIME,RESULT_STATE FROM ...'
Error: (dberror) 266 - inconsistent datatype: only numeric type is available for SUM/AVG/STDDEV/VAR function: line 43 col 7 (at pos 654)
If I exclude this part of sql select sum(LOADING_TIME) AS TOTAL_LOADING_TIME, then it works.
How can I solve the issue to get total_loading_time?
WITH l1 AS(
SELECT REMOTE_SOURCE_NAME,OWNER,NAME,MAX(START_TIME) START_TIME,RESULT_STATE
FROM "MEAG_EIM_SHARED"."meag.eim.shared::replication.Log"
WHERE TYPE = 'INITIAL' AND RESULT_STATE = 'COMPLETED'
AND REMOTE_SOURCE_NAME='RS_SDI_IMMO'
group by REMOTE_SOURCE_NAME,OWNER,NAME,RESULT_STATE
order by NAME ASC),
l2 AS
(SELECT REMOTE_SOURCE_NAME,OWNER,NAME,START_TIME,END_TIME,RESULT_STATE
FROM "MEAG_EIM_SHARED"."meag.eim.shared::replication.Log"
WHERE TYPE = 'INITIAL' AND RESULT_STATE = 'COMPLETED'
AND REMOTE_SOURCE_NAME='RS_SDI_IMMO'
group by REMOTE_SOURCE_NAME,OWNER,NAME,RESULT_STATE,START_TIME,END_TIME
order by NAME ASC)
select sum(LOADING_TIME) AS TOTAL_LOADING_TIME
from(
select layer1.REMOTE_SOURCE_NAME,layer1.OWNER,layer1.name,layer1.RESULT_STATE,layer1.start_time start_time,layer2.end_time end_time,
SECONDS_BETWEEN(layer1.START_TIME,layer2.END_TIME) || 's' LOADING_TIME
from l1 layer1 inner join l2 AS layer2
on layer1.start_time=layer2.start_time
order by name);

LOADING_TIME has the character ā€žsā€œ concatenated to it - that turns the numeric value into a string.
And for strings there is no SUM() function.
If having the ā€žsā€œ is important then adding it after the summation will fix the issue.
Otherwise, adding the unit denomination (I guess the s stands for seconds) to the column name would allow client tools to still work with the numeric value (I.e. when sorting)

Related

Issue With SQL Pivot Function

I have a SQL query where I am trying to replace null results with zero. My code is producing an error
[1]: ORA-00923: FROM keyword not found where expected
I am using an Oracle Database.
Select service_sub_type_descr,
nvl('Single-occupancy',0) as 'Single-occupancy',
nvl('Multi-occupancy',0) as 'Multi-occupancy'
From
(select s.service_sub_type_descr as service_sub_type_descr, ch.claim_id,nvl(ci.item_paid_amt,0) as item_paid_amt
from table_1 ch, table_" ci, table_3 s, table_4 ppd
where ch.claim_id = ci.claim_id and ci.service_type_id = s.service_type_id
and ci.service_sub_type_id = s.service_sub_type_id and ch.policy_no = ppd.policy_no)
Pivot (
count(distinct claim_id), sum(item_paid_amt) as paid_amount For service_sub_type_descr IN ('Single-occupancy', 'Multi-occupancy')
)
This expression:
nvl('Single-occupancy',0) as 'Single-occupancy',
is using an Oracle bespoke function to say: If the value of the string Single-occupancy' is not null then return the number 0.
That logic doesn't really make sense. The string value is never null. And, the return value is sometimes a string and sometimes a number. This should generate a type-conversion error, because the first value cannot be converted to a number.
I think you intend:
coalesce("Single-occupancy", 0) as "Single-occupancy",
The double quotes are used to quote identifiers, so this refers to the column called Single-occupancy.
All that said, fix your data model. Don't have identifiers that need to be quoted. You might not have control in the source data but you definitely have control within your query:
coalesce("Single-occupancy", 0) as Single_occupancy,
EDIT:
Just write the query using conditional aggregation and proper JOINs:
select s.service_sub_type_descr, ch.claim_id,
sum(case when service_sub_type_descr = 'Single-occupancy' then item_paid_amt else 0 end) as single_occupancy,
sum(case when service_sub_type_descr = 'Multi-occupancy' then item_paid_amt else 0 end) as multi_occupancy
from table_1 ch join
table_" ci
on ch.claim_id = ci.claim_id join
table_3 s
on ci.service_type_id = s.service_type_id join
table_4 ppd
on ch.policy_no = ppd.policy_no
group by s.service_sub_type_descr, ch.claim_id;
Much simpler in my opinion.
for column aliases, you have to use double quotes !
don't use
as 'Single-occupancy'
but :
as "Single-occupancy",

What is the syntax problem here using this subquery inside where clause

SELECT p.pnum, p.pname
FROM professor p, class c
WHERE p.pnum = c.pnum AND c.cnum = CS245 AND (SELECT COUNT(*) FROM (SELECT MAX(m.grade), MAX(m.grade) - MIN(m.grade) AS diff
FROM mark m WHERE m.cnum = c.cnum AND m.term = c.term AND m.section = c.section AND diff <= 20)) = 3
Incorrect syntax near ')'. Expecting AS, FOR_PATH, ID, or QUOTED_ID.
Consider the following example:
SELECT COUNT(1)
FROM SYSCAT.TABLES T
WHERE
(
-- SELECT COUNT(1)
-- FROM
-- (
SELECT COUNT(1)
FROM SYSCAT.COLUMNS C
WHERE C.TABSCHEMA=T.TABSCHEMA AND C.TABNAME=T.TABNAME
-- )
) > 50;
The query above works as is. But the problem is, that if you uncomment the commented out lines, you get the following error message: "T.TABNAME" is an undefined name. and least in Db2 for Linux, Unix and Windows.
You can't push external to the sub-select column references too deeply.
So, your query is incorrect.
It's hard to correct it, until you provide the task description with data sample and the result expected.
I can see a potential syntax errors: It seems that CS245 refers to a value c.cnum may take and not a column name. If that is the case, it should be enclosed in single quotes.

How to get ROW_NUMBER() in SQL?

I tried to get the row number using ROW_NUMBER() but it shows the following error:
can't format message 13:896 -- message file C:\WINDOWS\firebird.msg
not found. Dynamic SQL Error. SQL error code = -104. Token unknown -
line 2, column 66.
Here is my code:
SELECT avg(CSIDTL.RATING) ,SVD.SVCADVISORNAME, ROW_NUMBER() OVER(ORDER BY avg(CSIDTL.RATING) )
FROM T_APPT_BOOKING_MSTR MSTR ,T_APPT_CSI_SURVEY CSI,T_APPT_CSI_SURVEY_DTL CSIDTL,
T_SVC_SVCADVISOR_MASTER SVD
WHERE MSTR.APPTBKID = CSI.APPTBKID
AND CSI.CSI_SURVERYID = CSIDTL.CSI_SURVERYID
AND SVD.SVCADVISORID = MSTR.SVCADVISORID
AND CSI.FEEDBACK_STATUS = 'Y'
AND CSIDTL.question ='Service Advisor'
GROUP BY SVD.SVCADVISORNAME
ORDER by avg(CSIDTL.RATING)
The ROW_NUMBER() function was introduced with Firebird 3.0, released just few days ago. See release notes, chapter Window (Analytical) Functions for exact syntax. The error you get suggests you're using an older version of Firebird which doesn't have this feature.
I use this in Firebird 2.5
Reference: http://www.firebirdfaq.org/faq343/
SELECT rdb$get_context('USER_TRANSACTION', 'row#') as row_number, DUMMY, A.*
FROM your_table A
CROSS JOIN
(SELECT rdb$set_context('USER_TRANSACTION', 'row#',
COALESCE(CAST(rdb$get_context('USER_TRANSACTION', 'row#') AS INTEGER), 0) + 1) AS dummy
FROM rdb$database) dummy
Example for Firebird 3.0+
SELECT row_number() over(), t.* FROM test t
Other alternative in Firebird 2.5 is use of generators
CREATE GENERATOR tmp$rn;
UPDATE my_table t SET t.id_field = (SELECT FIRST 1 NEXT VALUE FOR tmp$rn AS "row_number"
FROM my_table ORDER BY another_field1 DESC, another_field2 DESC);
DROP GENERATOR tmp$rn;
This may be helpful,
Reference
Firebird 3.0 Language Reference - 10.4. Ranking Functions
Available in :DSQL, PSQL
Result type :BIGINT
Syntax
ROW_NUMBER () OVER <window-specification>
Returns the sequential row number in the partition of the result set, where 1 is the first row in each of the partitions.

ORA-00933 SQL command not properly ended

I need to convert MSSQL query to Oracle but end up with SQL command not properly ended.
Here is MSSQL query
SELECT * FROM [dbo].[trade] AS [Extent1]
WHERE EXISTS (
SELECT 1 AS [C1] FROM
[dbo].[findetail] AS [Extent2]
INNER JOIN [dbo].[transact] AS [Extent3] ON [Extent2].[transact] = [Extent3].[transact]
WHERE [Extent1].[trade] = [Extent2].[trade]
AND 'ACCR' = [Extent3].[subledger]
AND [Extent3].[date] = '2016-03-18T00:00:00'
)
Converting it to Oracle SQL I end with this.
SELECT * FROM trade Extent1
WHERE EXISTS
(SELECT 1 C1 FROM findetail Extent2
JOIN transact Extent3
ON Extent2.transact=Extent3.transact
WHERE Extent1.trade=Extent2.trade
AND 'ACCR'=Extent3.subledger
AND Extent3.date='2016-03-18T00:00:00'
);
and receive error above.
Date formats are different in Oracle. Perhaps something like this:
SELECT *
FROM trade Extent1
WHERE EXISTS (SELECT 1
FROM findetail Extent2 JOIN
transact Extent3
ON Extent2.transact = Extent3.transact
WHERE Extent1.trade = Extent2.trade AND
Extent3.subledger = 'ACCR' AND
Extent3."date" = DATE '2016-03-18'
);
DATE is a reserved word so needs to the surrounded in double quotes and, I am assuming that it is of DATE data type so you will probably need to convert the string:
SELECT *
FROM trade t
WHERE EXISTS (
SELECT 1
FROM findetail f
JOIN transact r
ON f.transact = r.transact
WHERE t.trade = f.trade
AND 'ACCR' = r.subledger
AND r."DATE" = TO_DATE( '2016-03-18T00:00:00', 'YYYY-MM-DD"T"HH24:MI:SS' )
);
If you just use the string in r."DATE" = '2016-03-18T00:00:00' then Oracle will implicitly try to convert the string literal using the TO_DATE() function with the NLS_DATE_FORMAT session parameter as the format mask. If they match then it will work but this is a client variable so can be changed and then the query will break without the code having changed (and be a pain to debug). The simple answer is to ensure that you compare date value by either using TO_DATE() and specifying the format mask (as per the query above) or to use an ANSI date literal DATE '2016-03-18' (which is independent of the NLS settings).

"Circular reference caused by ..." error in Access SQL (but not in T-SQL)

I have the following SQL statement which returns the desired result in SQL Server 2012:
SELECT
S.ONOMA
, S.DIEY
, S.POLH
, S.TK
, S.IDIOT
, S.KODIKOS
, S.AFM
FROM
SYNERG AS S
INNER JOIN
(SELECT
G.AFM, MIN(KODIKOS) AS KODIKOS
FROM SYNERG AS G
WHERE LEN(ISNULL(AFM, '')) != 0
GROUP BY AFM) AS I ON S.KODIKOS = I.KODIKOS
ORDER BY
S.AFM
but when I run the same SQL statement in MS Access 2007 I get an error:
Circular reference caused by 'KODIKOS' in query definition's SELECT list.
Any help would be appreciated.
As explained in the link by HansUp:
The alias of a calculated field cannot be identical to any of the field names used to calculate the field.
This can be rather annoying (esp. if it is a field that is returned by the query), but there is no way around it.
So you need to change the alias, e.g.:
SELECT
S.ONOMA
, S.DIEY
, S.POLH
, S.TK
, S.IDIOT
, S.KODIKOS
, S.AFM
FROM
SYNERG AS S
INNER JOIN
(SELECT
G.AFM, MIN(KODIKOS) AS MinKODIKOS
FROM SYNERG AS G
WHERE LEN(Nz(AFM, '')) <> 0
GROUP BY AFM) AS I ON S.KODIKOS = I.MinKODIKOS
ORDER BY
S.AFM
Note also that an IsNull() function exists in Access, but has a different meaning (it takes one argument and returns a Boolean). The corresponding function is Nz()
And (thanks #HansUp), the unequal operator is <>, not !=. I always use <> in SQL Server too, no need to make things more complicated than necessary. :)