Postgresql CASE statement schema error - postgresql

I'm getting a 3F000 error from the following CASE statement.
select
entity.level1
, sum(trans_clean.amount_calculated) as total_spend
, sum(CASE WHEN extract(year from age(supplier.open_date::trans_clean.date_calculated)) <= 5 AND org_type = 'SMALL BUSINESS' THEN trans_clean.amount_calculated END) small_young
, trans_clean.date_calculated
from
entity, supplier, trans_clean
where
trans_clean.supplier_id = supplier.supplier_id and
trans_clean.entity_id = entity.entity_id and
date_calculated > '2011-12-01'
group by
entity.level1
, total_spend
, small_young
, trans_clean.date_calculated
;
The error is as follows:
ERROR: schema "trans_clean" does not exist
SQL state: 3F000
The statement works without the CASE line, I'm running the query in PGAdmin III and the right schema (public) is definitely selected.

Related

Can someone help me with the databricks timestamp/timezone syntax issue that im facing while executing my query?

I am moving my data pointing from SSMS (SQL Server Management Studio) to Databricks. There will be syntax change in the query in databricks as compared to SSMS query. I am not familiar with databricks. So, I am trying to do the same query in databricks as well but, it is showing me error. How should i correct the syntax now? The error is where the conversion is happening to PST timezone. Can anyone help me with this ?
The SQL query is:
select
case
when category_name = 'Hardware' then 'Hardware'
when category_name = 'Services' then 'Services'
when category_name = 'Software' then 'Software'
when category_name = 'Subscription' then 'Cloud'
end as category_name,
sum(item_price * line_item_quantity) as order_amount,
CUSTOMER_ID
from
curated_delta.order_details
where
parentkit_id = 0
and category_name in ('Hardware', 'Software', 'services', 'Subscription')
and category_name is not null
and order_date >= cast(cast(dateadd(dd, -365, convert(datetime, sysdatetimeoffset() AT TIME ZONE 'pacific standard time')) as date) as datetime)
group by
category_name, CUSTOMER_ID
order by
1
The error I get is:
Error in SQL statement: ParseException:
no viable alternative at input 'cast(cast(dateadd(dd,-365,convert(datetime,sysdatetimeoffset() AT'(line 6, pos 79)

NOT IN SUBQUERIES SQL compilation error: Unsupported subquery type cannot be evaluated

I would like to understand an issue when i am querying two table with pretty similar queries.
You can see tables as below:
When i execute this one, i have no errors and it works perfectly:
SELECT
DISTINCT(A."Ref"),
A."Period",
A."Country",
A."Tag",
A."Name",
1 AS "Won",
0 AS "Lost"
FROM
"main_table1" A
WHERE
A."Period" = DATE_TRUNC('MONTH', A."Date Begin")
AND A."Ref" NOT IN (
SELECT
B."Ref"
FROM
"main_table1" B
WHERE
B."Period" = DATEADD(MONTH, -1, A."Period")
)
When i execute this one i have the error below the query. Can you telle me why and how workaround this ?
SELECT
A."Ref",
A."Name",
A."Country",
A."Tag",
A."Period",
1 AS "Won",
0 AS "Lost"
FROM
"main_table2" A
WHERE
A."Ref" NOT IN (
SELECT
B."Ref"
FROM
"main_table2" B
WHERE
B."Period" = A."Report_Period_M-1"
)
SQL compilation error: Unsupported subquery type cannot be evaluated
Wouldn't just using a LEFT JOIN directly work?
SELECT
A."Ref",
A."Name",
A."Country",
A."Tag",
A."Period",
1 AS "Won",
0 AS "Lost"
FROM "main_table2" A
LEFT JOIN "main_table2" B
ON A."Report_Period_M-1" = B."Period"
WHERE A."Ref" IS NULL

SQL Error: ERROR: not all tokens processed

Am getting below error in Postgres while executing insert and delete queries. I have around 50 inserts and 50 delete statements. When executed an getting the error as,
SQL Error: ERROR: not all tokens processed
The error is not consistent all the time,
For example,
My 20th delete statement is getting failed
Next time when the same queries are executed, 25th delete statement is getting failed
And when those statements are executed alone, there is no failure.
Not sure if it is a database load issue or infrastructure related issue.
Any suggestion would be helpful
Below is the query,
WITH del_table_1 AS
(
delete from table_1 where to_date('01-'||col1,'DD-mm-YYYY') < current_date-1
RETURNING *
)
update control_table set deleted_count = cnt, status = 'Completed',
update_user_id = 'User', update_datetime = current_date from
(select 'Table1' as table_name, count(*) as cnt from del_table_1) aa
where
control_table.table_name = aa.table_name
and control_table.table_name = 'Table1'
and control_table.status = 'Pending';

group by error with postgres and pomm orm

I want to execute the following SQL query :
SELECT date, COUNT(id_customers)
FROM event
WHERE event_id = 3
GROUP BY date
When I try this query in my database, it works perfectly. But in my code I get an error which I can't resolve.
I use symfony2 with the orm pomm. It's Postgresql.
Here is my code :
$sql = "SELECT e.date, COUNT(id_customers) FROM event e WHERE event_id = $* GROUP BY e.date";
return $this->query($sql, [$eventId])->extract();
Here is the error :
request.CRITICAL: Uncaught PHP Exception InvalidArgumentException:
"No such field 'id'. Existing fields are {date, count}"
at /home/vagrant/sourcefiles/vendor/pomm-project/model-manager/sources/lib/Model/FlexibleEntity/FlexibleContainer.php line 64
{"exception":" [object] (InvalidArgumentException(code: 0): No such field 'id'.
Existing fields are {date, count}
at /home/vagrant/sourcefiles/vendor/pomm-project/model-manager/sources/lib/Model/FlexibleEntity/FlexibleContainer.php:64)"} []
So I tried to had the id in my select, by I get this error :
request.CRITICAL: Uncaught PHP Exception
PommProject\Foundation\Exception\SqlException: "
SQL error state '42803' [ERROR] ==== ERROR: column "e.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT e.id, e.date, COUNT(id_customers) FROM event e WHERE ... ^
==== «PREPARE === SELECT e.id, e.date, COUNT(id_customers) FROM event e WHERE event_id = $1 GROUP BY e.date ===»." at /home/vagrant/sourcefiles/vendor/pomm-project/foundation/sources/lib/Session/Connection.php line 327 {"exception":"[object] (PommProject\Foundation\Exception\SqlException(code: 0): \nSQL error state '42803' [ERROR]\n====\nERROR: column \"e.id\" must appear in the GROUP BY clause or be used in an aggregate function\nLINE 1: SELECT e.id, e.date, COUNT(id_customers) FROM event e WHERE ...\n ^\n\n====\n«PREPARE ===\nSELECT e.id, e.date, COUNT(id_customers) FROM event e WHERE event_id = $1 GROUP BY e.date\n ===». at /home/vagrant/sourcefiles/vendor/pomm-project/foundation/sources/lib/Session/Connection.php:327)"} []
The only thing that works is when I had the id in the group by, but this is not the result I want.
Someone can explain me why this is working in the database and not in the php ?
this is because you are fetching flexible entities without their primary key. There is an identity mapper behind the scene that ensure fetching twice the same entity will return the same instance.
In this case, you do not need to fetch entities (hence the extract after the query). So you can just use the QueryManager pooler to return converted arrays like the following:
$sql = "SELECT e.date, COUNT(id_customers) FROM event e WHERE event_id = $* GROUP BY e.date";
// Return an iterator that fetches converted arrays on demand:
return $this
->getSession()
->getQueryManager()
->query($sql, [$eventId])
;
i think its because the alias,
try this
$sql = "SELECT e.date, COUNT(e.id_customers) FROM event e WHERE event_id = $* GROUP BY e.date";
return $this->query($sql, [$eventId])->extract();
This is exactly how GROUP BY works in PostgreSQL:
When GROUP BY is present, it is not valid for the SELECT list
expressions to refer to ungrouped columns except within aggregate
functions, since there would be more than one possible value to return
for an ungrouped column.
It means that each field in your query either must be present in GROUP BY statement or handled by any of the aggregation functions. This is one of the differences between GROUP BY in MySQL and PostreSQL.
In other words you can add id at GROUP BY statement and do not worry about it ;)

Microsoft Report Builder with Postgresql and multiple CTEs

I have a problem creating DataSets with CTE in the current Microsoft Report Designer.
My DataSource is a PostgreSQL Database and I use the current Version of PGNP to connect to.
The connection works fine, I can create DataSets based on Queries and get my data.
BUT if I try to create more complex queries, like for example with multiple CTE, I won't get any fields.
Exampe:
SELECT 'Test' as test
Will return one column (test) with one row (Test)
WITH Test as (SELECT 'Test' as test)
SELECT Test
, 'Success' as result
FROM Test
Will return two columns (test, result) with one row (Test, Success)
Till now, everything is ok.
But if I want to use more then one CTE, I have to face the following problems:
WITH Test as (SELECT 'Test' as test),
TestB as (SELECT 'Test B' as test)
SELECT ta.test, tb.test, 'Success' as result
FROM Test ta, TestB tb
Will fail with the following error message:
"Undefined table Test"
;WITH Test as (SELECT 'Test' as test),
TestB as (SELECT 'Test B' as test)
SELECT ta.test, tb.test, 'Success' as result
FROM Test ta, TestB tb
Will return no columns and no rows.
Any idea why this happens?
Edit A:
Here a (shorternd) Version of my actual query:
WITH calls AS (
SELECT acv.id
, acv.created
, acv.state
, acv.statistics_category
, acv.duration
, aqv.id as queue_id
, aqv.name as queue_name
, acv.target
, acv.target_name
, acv.queue_time
, acv.ringing_duration
, acv.hold_time
FROM acd_call_view acv
LEFT JOIN acd_queue_view aqv ON (aqv.id = acv.fk_acdqueue_id)
ORDER BY acv.id, acv.created
),
calls_answered as (
SELECT *
FROM calls
WHERE statistics_category = 'answered'
)
SELECT * FROM calls_answered
Result: "Unknown table calls"
Edit B:
Sorry, had two leftovers from the shortening remaining in the query
Edit C:
Tested Query in pgAdmin III: Working
Tested Query in JasperSoft Studio: Working
Tested Query in MS Report Builder with PGNP: "Undefined table calls"
Edit D:
As soon as I remove the second CTE, I get results
WITH calls AS (
SELECT acv.id
, acv.created
, acv.state
, acv.statistics_category
, acv.duration
, aqv.id as queue_id
, aqv.name as queue_name
, acv.target
, acv.target_name
, acv.queue_time
, acv.ringing_duration
, acv.hold_time
FROM acd_call_view acv
LEFT JOIN acd_queue_view aqv ON (aqv.id = acv.fk_acdqueue_id)
ORDER BY acv.id, acv.created
)
SELECT * FROM calls
Works fine, so I get results, the PGNP Ole DB Driver seems to work fine, the connection is up, everything is okay.
As soon, as I add the second CTE, I get the error
Works here (just plain psql terminal) , so the error must be in your framework/client application:
CREATE TABLE acd_call_view
( id INTEGER NOT NULL
, created timestamp
, state integer
, statistics_category text
, duration INTEGER
, target INTEGER
, target_name INTEGER
, queue_time INTEGER
, ringing_duration INTEGER
, hold_time INTEGER
, fk_acdqueue_id INTEGER
);
CREATE TABLE acd_queue_view
( id INTEGER NOT NULL
, name text
);
WITH calls AS (
SELECT acv.id
, acv.created
, acv.state
, acv.statistics_category
, acv.duration
, aqv.id as queue_id
, aqv.name as queue_name
, acv.target
, acv.target_name
, acv.queue_time
, acv.ringing_duration
, acv.hold_time
FROM acd_call_view acv
LEFT JOIN acd_queue_view aqv ON aqv.id = acv.fk_acdqueue_id
ORDER BY acv.id, acv.created
)
, calls_answered as (
SELECT *
FROM calls
WHERE statistics_category = 'answered'
)
SELECT * FROM calls_answered
;
Okay, here the solution:
Seems like the PGNP OleDB Driver cannot handle multiple CTEs.
Installed the ODBC Driver and configured a new DateSource via ODBC.
Now I get my results and am happy :-)
Nevertherless, thank you joop for your time.
I contacted PGNP support, and they responded quickly that the bugs in the CTEs handling were fixed in build 1.4.0.3425.