PostgreSQL : Operator does not exist: Integer < Interval - sql

I have wrote a query so I can view people who are overdue an order based on their average order dates. The query is to be ran on a PostgreSQL database, and will be executed from a Java process.
However in the line :
CASE WHEN
(max(date_trunc('day', dateordered))-
min(date_trunc('day', dateordered)) ) /
count(distinct dateordered) + 5 <
date_trunc('day',now()) -
max(date_trunc('day', dateordered)) THEN 'ORDEROVERDUE' ELSE
null
END
I receive the error message :
Operator does not exist : integer < interval
I have read a lot of questions which have a similar issue, but none which seem to fix my particular issue.
If I alter my query to this :
CASE WHEN
(max(dateordered::date) - min(dateordered::date) )/
count(distinct dateordered) + 5 <
now()::date - max(dateordered::date) THEN
'ORDEROVERDUE' ELSE null
END
Then it runs on the database, however I can't get this syntax to work in my process in eclipse.
My understanding of SQL is letting me down. I understand the general reason behind the error, but I am unable to create a solution.
Is there a way of altering this line in a way which removes the error and I can still get the desired result?

Related

TrinoUserError (type=USER_ERROR, name=SYNTAX_ERROR, message="line 7:26: mismatched input 'COUNT'. Expecting: '*', <expression>")

I am using dbt-trino and for some reason, it doesn't understand the MySQL query that works fine by executing it directly on MySQL. In this query, I want to select and group records that have been created during the previous month.
The Query:
SELECT order_location, COUNT(*) as order_count
FROM {{ ref('x_stg_order_fields') }}
WHERE
created_at >= DATE_FORMAT( CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01' )
AND
created_at < DATE_FORMAT( CURRENT_DATE, '%Y/%m/01' )
GROUP BY order_location
While this query works fast and successfully directly on MySQL, it returns this error when executing with dbt run:
TrinoUserError(type=USER_ERROR, name=SYNTAX_ERROR, message="line 7:53: mismatched input 'COUNT'. Expecting: '*', <expression>")
Does this mean that dbt-trino doesn't support all MySQL functions?
That error is coming from your database, not from dbt itself. dbt does not parse your SQL commands, it just passes them through to your connected database.
My guess is that {{ ref('x_stg_order_fields' }} may be referring to an ephemeral model that contains a syntax error, or possibly a field named count that isn't quoted?
You can confirm or disprove that by looking at the SQL that dbt tried to run in your database, by inspecting the target directory in your project. Specifically, target/run/path/to/your_model.sql will show you the actual command being executed. You should be able to check line 7, col 53 in that file, and you will see the code that trino is erroring about.

Apache Drill Timestampdiff on Oracle DB

Hey everyone im relativly new to Apache Drill and im having troubles converting my Oracle specific sql scripts (pl/sql) to Drill based querys.
For example i have a Scripts who checks for processed data in the last X Days.
In this script im using the the sysdate function.
Here is my old script:
SELECT i.id,i.status,status_text,i.kunnr,i.bukrs,i.belnr,i.gjahr,event,i.sndprn,i.createdate,executedate,tstamp,v.typ_text,i.docnum,i.description, i.*
FROM in_job i JOIN vstatus_injob v ON i.id= v.id
WHERE 1=1
AND i.createdate > sysdate - 30.5
order by i.createdate desc;
When i looked up in terms of drill specific Datetime Diff functions i found "TIMESTAMPDIFF".
So here is my "drillified" script:
SELECT i.id, i.status, status_text, i.kunnr, i.bukrs, i.belnr, i.gjahr, i.event, i.sndprn, i.createdate, i.executedate, i.tstamp,v.typ_text,i.docnum,i.description,i.*
FROM SchemaNAME.IN_JOB i JOIN SchemaNAME.VSTATUS_INJOB v ON i.id=v.id
WHERE TIMESTAMPDIFF(DAY, CURRENT_TIMESTAMP, i.createdate) >=30
And the Error that is returned reads like this:
DATA_READ ERROR: The JDBC storage plugin failed while trying setup the SQL query.
By further inspection i can see the Oracle specific error that reads:
Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "TIMESTAMPDIFF": invalid ID
So now my question:
I thought apache drill replaces the function "TIMSTAMPDIFF" at runtime. But from what i can see in the logs its more like that Drill Hands over the Function Call "TIMESTAMPDIFF" to the Oracle database.
If thats true, how could i change my script to calculate the time difference (in days) and compare it to an int (ie 30 in the script).
If i use sysdate like above Apache Drill jumps in and says it doesnt know "sysdate".
How would you guyes handle that?
Thanks in advance and so long
:)
I have found a solution...
Just in Case someone (or even me in the future) is having a similar problem.
{
"queryType": "SQL",
"query": "select to_char(SELECT CURRENT_TIMESTAMP - INTERVAL XX MONTH FROM (VALUES(1)),'dd.MM.yy')"
}
With some to_char and the use of the CURRENT_TIMESTAMP - Interval Function Calls i can get everything i needed.
I took the query above packed it into an Grafana Variable, named it "timeStmpDiff" and then queried everything with an json Api Call to my Drill instance.
Basically:
"query" : "SELECT i.id, i.status, status_text, i.kunnr, i.bukrs, i.belnr, i.gjahr, i.event, i.sndprn, i.createdate, i.executedate, i.tstamp,v.typ_text,i.docnum,i.description,i.* FROM ${Schema}.IN_JOB i JOIN ${Schema}.VSTATUS_INJOB v ON i.id=v.id WHERE i.createdate >= '${timeStmpDiff}' order by i.createdate desc"
You can, of course query it in on go with an subselect.
But because i use grafana it made sense to me to bundle that in a Variable.

Divide by zero error when converting Access to SQL Server query

I am trying to convert an Access query to one that works in SQL server. The original query in Access works perfectly well (just terribly slow).
I only changed things slightly to make it compatible with SQL server instead of Access, like changing "NOW()" to "GETDATE()" and we can no longer divide aliases.
Running this query in SQL Server:
SELECT batches.[price-group],
[development].verifier,
Count([development].company) AS SENT,
Sum([order] *- 1) AS ORDS,
Count([development].company) / Sum([order] *- 1) AS PCT
FROM [development]
INNER JOIN batches
ON [development].batch = batches.batch
WHERE (( ( [development].[mail-date] ) < Getdate() - 50 ))
GROUP BY batches.[price-group],
[development].verifier
HAVING (( ( batches.[price-group] ) = 'pgb' ))
ORDER BY batches.[price-group],
[development].verifier,
Count([development].company) DESC;
Returns this error:
Msg 8134, Level 16, State 1, Line 1 Divide by zero error encountered.
Only real change, was like I said, in Access we could do this
[ords] / [sent] AS PCT
Any help will be appreciated, I'm not sure exactly why it isn't working! Removing the converted line above, does work in SQL server without any errors.
Thank you!
Use NULLIF():
Count([development].company) / NULLIF(Sum([order] * -1), 0) AS PCT

Passing parameters in HIVE query

I need to pass a parameter into an HQL at execution time. For this we have updated the .param file with the required value. Now I am facing issue in using it.
SELECT * FROM temp_table A
WHERE PRODT_CTGRY_CD = 'CAR' AND
(
(DATE(A.CUST_BRTH_DT) BETWEEN concat(${hiveconf:PRODYEAR} - 13 ,"-02","-28") and concat(${hiveconf:PRODYEAR} - 7 ,"-03","-01")
AND DATE(A.TERM_DT) >= concat(${hiveconf:PRODYEAR} - 1 ,"-03","-31")
)
In the above query if I don't include the condition of term_dt the query is running fine. However when I include that I am getting an error as below:
FAILED: ClassCastException org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableIntObjectInspector cannot be cast to org.apache.hadoop.hive.serde2.objectinspector.primitive.BooleanObjectInspector (state=42000,code=40000)
Can someone let me know what needs to be done here?

ERROR - SQL Error '[Cache ODBC][State : S1000][Native Code 29]

I have been using the query below and it was working fine but now it's giving a SQL error.
There were no changes made that could cause this to stop working.
There is no Field 'APPLICATIONID' in the table.
QueueSQL=select distinct (convert(char(5),SkillsetID)+'='+Skillset) from iagentbySkillsetStat where ApplicationID > 10000
QueueMappingSQL=SELECT DISTINCT (convert(char(5),SkillsetID)+'='+Skillset), SkillsetID FROM iagentbySkillsetStat iagentbySkillsetStat WHERE (iagentbySkillsetStat.ApplicationID>10000)
DB- Intersystems Cache
Error details for the log files are below.
14/09/2016 11:20:05 a.m. > ERROR - SQL Error '[Cache ODBC][State : S1000][Native Code 29]
[C:\xlink\xlink Compiled Package\Xlink Application\Isps_Ul.exe]
[SQLCODE: <-29>:<Field not found in the applicable tables>]
[Cache Error: <<SYNTAX>errdone+2^%qaqqt>]
[Details: <Prepare>]
[%msg: < SQL ERROR #29: Field 'APPLICATIONID' not found in the applicable tables^select distinct ( convert ( char ( 5 ) , SkillsetID ) + :%qpar(1) + Skillset ) from iagentbySkillsetStat where ApplicationID >>]'
Question was also asked at InterSystems Developer Community, where I noticed that table names are different. So, the answer is, that table name is suddenly changed somehow.