Unable to access column alias in WHERE clause - sql

I am trying to filter rows from my Postgres database with below query. Everything works fine but when I try to check if latesttask column is null or has some value then it shows error:
error: column "latesttask" does not exist
SELECT *,
(
SELECT
JSON_BUILD_OBJECT(
'id', taskhistories.id, 'task', taskhistories.task,
'taskname', t.name, 'project', taskhistories.project,
'projectname', p.name, 'started_at',
taskhistories.started_at, 'stopped_at',
taskhistories.stopped_at
)
FROM
tasks AS t,
projects AS p,
latesttasks,
taskhistories
WHERE
taskhistories.user = users.id
AND latesttasks.task = t.id
AND latesttasks.project = p.id
AND taskhistories.id = latesttasks.taskhistory
AND (
LOWER(t.name) LIKE '%we%'
OR LOWER(p.name) LIKE '%we%'
)
) as latestttask
FROM
users
WHERE
(
latesttask IS NULL
AND (
LOWER(name) LIKE '%we%'
OR LOWER(email) LIKE '%we%'
)
OR latesttask IS NOT NULL
)

One "t" to many in your column alias latestttask.
But, more importantly, you cannot reference output column names in the WHERE clause anyway. There would have to be a column users.latesttask to make the WHERE clause work.
This would be a working equivalent with a LEFT JOIN to a LATERAL subquery:
SELECT *
FROM users u
LEFT JOIN LATERAL (
SELECT json_build_object(
'id', h.id, 'task', h.task,
'taskname', t.name, 'project', h.project,
'projectname', p.name, 'started_at', h.started_at,
'stopped_at', h.stopped_at) AS latesttask
FROM tasks t
JOIN latesttasks l ON l.task = t.id
JOIN projects p ON p.id = l.project
JOIN taskhistories h ON h.id = l.taskhistory
WHERE h.user = u.id
AND (lower(t.name) LIKE '%we%'
OR lower(p.name) LIKE '%we%')
) l ON true
WHERE l.latesttask IS NOT NULL
OR lower(u.name) LIKE '%we%'
OR lower(u.email) LIKE '%we%';

Please try with...
Select * from (SELECT
*,
(
SELECT
JSON_BUILD_OBJECT(
'id', taskhistories.id, 'task', taskhistories.task,
'taskname', t.name, 'project', taskhistories.project,
'projectname', p.name, 'started_at',
taskhistories.started_at, 'stopped_at',
taskhistories.stopped_at
)
FROM
tasks AS t,
projects AS p,
latesttasks,
taskhistories
WHERE
taskhistories.user = users.id
AND latesttasks.task = t.id
AND latesttasks.project = p.id
AND taskhistories.id = latesttasks.taskhistory
AND (
LOWER(t.name) LIKE '%we%'
OR LOWER(p.name) LIKE '%we%'
)
) as latesttask
FROM
users ) a
WHERE
(
latesttask IS NULL
AND (
LOWER(name) LIKE '%we%'
OR LOWER(email) LIKE '%we%'
)
OR latesttask IS NOT NULL
)

Related

MariaDB / MySQL CTE Raw SQL ambiguous error

I have this RAWSQL query
with
group as (
select * from groups where id = ?
),
attributes as (
select JSON_ARRAYAGG(
JSON_OBJECT('id', a.id,'name', a.name ))
from attributes a
join groups g on g.id = ?
join attribute_group ag on ag.group_id = g.id
and ag.attribute_id = a.id
),
templates as (
select JSON_ARRAYAGG(
JSON_OBJECT('id', t.id,'name', t.name))
from templates t
join groups g on g.id = ?
join group_template gt on gt.group_id = g.id
and gt.template_id = t.id
)
select *,
(select cast(count(*) as char) from attribute_group where group_id = ? ) groups_count,
(select * from groups) groups,
(select cast(count(*) as char) from group_template where group_id = ? ) templates_count,
from group
I have this error
Query 1 ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'group as (
The documentation advises to not use reserved words like group and groups. They are reserved characters and should only be used for things like the GROUP BY statement:
GROUP (R)
GROUPING (R); added in 8.0.1 (reserved)
GROUPS (R); added in 8.0.2 (reserved)
Outside of that, I noticed a few syntax errors:
If you have a table named GROUP, which it looks like you do, you
can escape the reserved word by using back ticks `` or double quotes "" (I.e. `group`, "group").
Remove the comma , after templates_count,.
Replace ? with a valid id column value (I used 1 below).
Like so:
with
`group` as (
select * from `groups` where id = 1
),
attributes as (
select JSON_ARRAYAGG(
JSON_OBJECT('id', a.id,'name', a.name ))
from attributes a
join `groups` g on g.id = 1
join attribute_group ag on ag.group_id = g.id
and ag.attribute_id = a.id
),
templates as (
select JSON_ARRAYAGG(
JSON_OBJECT('id', t.id,'name', t.name))
from templates t
join `groups` g on g.id = 1
join group_template gt on gt.group_id = g.id
and gt.template_id = t.id
)
select *,
(select cast(count(*) as char) from attribute_group where group_id = 1 ) groups_count,
(select * from `groups`) `groups`,
(select cast(count(*) as char) from group_template where group_id = 1 ) templates_count
from `group`

SQL select specific rows from subquery and insert into row_to_json

I have a view for which I have created several subqueries, I'm trying to return one of the subqueries as json using -
row_to_json(err.*) as overall_totals
The subquery -
left join
(
SELECT q.id, SUM(q.total) AS total,
jsonb_agg(jsonb_build_object('count', q.total, 'type', q.name)) AS totals
FROM (
SELECT r.id AS id, e.name, COUNT(de.value_id) AS total
FROM table_c de
JOIN tests.error e
ON e.id = de.value_id
JOIN table_a p
ON de.process_id = p.id
Join table_b r on p.root = r.id
GROUP BY e.name, r.id ) q
GROUP BY q.id
) err on err.id = rs.id
This works fine and returns as json, however, I only want to return total and totals of the "err" sub-query and not q.id. I need the q.id in the sub-query so that I can join the query onto the rest of the view but I don't want it to be stored in overall_totals. How can I get around this? Is it possible to select certain values into row_to_json?
If you are fine with returning jsonb instead of json, then you can use the - operator:
to_jsonb(err.*) - 'id' as overall_totals
You can add more subquery, something like this
SELECT row_to_json(err2.*) as overall_totals
FROM
(
SELECT err.total, err.totals
FROM XXX_TABLE RS
left join
(
SELECT q.id, SUM(q.total) AS total, jsonb_agg(jsonb_build_object('count', q.total, 'type', q.name)) AS totals
FROM
(
SELECT r.id AS id, e.name, COUNT(de.value_id) AS total
FROM table_c de
JOIN tests.error e
ON e.id = de.value_id
JOIN table_a p
ON de.process_id = p.id
Join table_b r on p.root = r.id
GROUP BY e.name, r.id
) q
GROUP BY q.id
) err on err.id = rs.id
) err2

Postgres - how to build array in select with all rows ids

I would like to make something like this. Build array that I will have ids of all selected rows.
SELECT p.*,
array_agg(p.id) as places_ids,
(CASE
WHEN EXISTS(
SELECT id
FROM user_favorites uf
WHERE uf.place_id = p.id
AND uf.user_id = :userId
AND uf.deleted_at IS NULL
)
THEN true
ELSE false
END ) AS favorite
FROM (SELECT
DISTINCT ON (urv.object_id)
urv.id as recent_id,
p.id,
p.name,
p.address,
p.pictures
FROM user_recent_visits urv
JOIN places p on urv.object_id = p.id
WHERE urv.user_id = :userId
AND urv.object_type = :type
AND p.deleted_at IS NULL
AND p.status = 2
AND p.active = true
) AS p
GROUP BY p.recent_id, p.id, p.name, p.address
ORDER BY p.recent_id LIMIT 5
EDIT:
Full Error:
SQLSTATE[42883]: Undefined function: 7 ERROR: unknown compare operator for typ json LINE 30: ... GROUP BY
p.recent_id, p.id, p.name, p.address,... ^ (SQL: SELECT p.*,
array_agg(json_build_array(p.id)) as places_ids, (CASE WHEN EXISTS(
SELECT id FROM user_favorites uf WHERE uf.place_id = p.id AND
uf.user_id = :userId AND uf.deleted_at IS NULL ) THEN true ELSE false
END ) AS favorite FROM (SELECT DISTINCT ON (urv.object_id) urv.id as
recent_id, p.id, p.name, p.address, p.pictures FROM user_recent_visits
urv JOIN places p on urv.object_id = p.id WHERE urv.user_id = :userId
AND urv.object_type = :type AND p.deleted_at IS NULL AND p.status = 2
AND p.active = true ) AS p GROUP BY p.recent_id, p.id, p.name,
p.address, p.pictures ORDER BY p.recent_id LIMIT 5 )
But in this case I have error "unknown compare operator". So how to write this query to get that all ids as array.
Other question. Is it possible to do it without GROUP BY?
Thank you

Error in on clause comparison - Big Query

The following big query code gives the following error.
select
selected_date date,
pp.name property,
bb.bookings bb,
av.available vailable,
from
(SELECT DATE(DATE_ADD(TIMESTAMP("2017-10-01"), pos - 1, "DAY")) AS selected_date
FROM (
SELECT ROW_NUMBER() OVER() AS pos, *
FROM (FLATTEN((
SELECT SPLIT(RPAD('', 1 + DATEDIFF(TIMESTAMP(CURRENT_DATE()), TIMESTAMP("2017-10-01")), '.'),'') AS h
FROM (SELECT NULL)),h
)))) v
cross join
(select p.name name from [roomsproperties.properties] p where p.name not like '%test%' group by name) as pp
left join
(select sum(b.rooms) bookings,
p.name property,
b.checkin checkin,
b.checkout checkout
from [bookings.bookings] b
left join [roomsproperties.rooms] r on r.id = b.room_id
left join [roomsproperties.properties] p on p.id = r.property_id
where p.name not like '%test%'
and b.status not in('Rejected', 'Cancelled - By customer', 'OTP Not Varified')
group by property,checkin,checkout
) as bb on pp.name = bb.property and (v.selected_date between bb.checkin and bb.checkout)
left join
(select sum(r.quantity) available,
p.name property,
date(r.created_at) date
from [roomsproperties.rooms] r
left join [roomsproperties.properties] p on p.id = r.property_id
group by property, date
) av on pp.name = av.property and v.selected_date >= av.date
The error is,
Error: ON clause must be AND of = comparisons of one field name from each table, with all field names prefixed with table name. Consider using Standard SQL
Can any one help
You should try:
(select ...) as bb on pp.name = bb.property
WHERE v.selected_date between bb.checkin and bb.checkou
and:
(select ...) as av on pp.name = av.property
WHERE v.selected_date >= av.date

Why is Oracle REPLACE function not working for this string?

We have a pattern we use all the time and this is usually pretty straightforward.
sortOrder IN VARCHAR2 := 'Title'
query VARCHAR2(32767) := q'[
SELECT
Columns
FROM tables
ORDER BY {sortOrder}
]';
query := REPLACE(query, '{sortOrder}', sortOrder);
But for this string it is not working:
WITH appl_List
AS
(
SELECT DISTINCT
appls.admin_phs_ORG_code || TO_CHAR(appls.serial_num, 'FM000000') AS core_proj_number,
appls.Appl_ID
FROM TABLE(:portfolioTable) appls
),
g1SupportingProjCount AS
(
SELECT
gen1grants.silverchair_id,
COUNT(DISTINCT al.Appl_ID) AS ApplCount
FROM
appl_List al
JOIN cg_cited_reference_gen1_grant gen1grants
ON al.core_proj_number = gen1grants.ic_serial_num
JOIN cg_cited_reference_gen1 gen1refs
ON gen1grants.silverchair_id = gen1refs.silverchair_id
GROUP BY gen1grants.Silverchair_id
),
g1SupportedPubCount AS
(
SELECT
gen1grants.silverchair_id,
COUNT(DISTINCT gen1refs.gen1_wos_uid) AS PubCount
FROM
appl_List al
JOIN cg_cited_reference_gen1_grant gen1grants
ON al.core_proj_number = gen1grants.ic_serial_num
JOIN cg_cited_reference_gen1 gen1refs
ON gen1grants.silverchair_id = gen1refs.silverchair_id
GROUP BY gen1grants.Silverchair_id
),
g2SupportingProjCount AS
(
SELECT
gen2grants.silverchair_id,
COUNT(DISTINCT al.Appl_ID) AS ApplCount
FROM
appl_List al
JOIN cg_cited_reference_gen2_grant gen2grants
ON al.core_proj_number = gen2grants.ic_serial_num
JOIN cg_cited_reference_gen2 gen2refs
ON gen2grants.silverchair_id = gen2refs.silverchair_id
GROUP BY gen2grants.Silverchair_id
),
g2SupportedPubCount AS
(
SELECT
gen2grants.silverchair_id,
COUNT(DISTINCT gen2refs.gen2_wos_uid) AS PubCount
FROM
appl_List al
JOIN cg_cited_reference_gen2_grant gen2grants
ON al.core_proj_number = gen2grants.ic_serial_num
JOIN cg_cited_reference_gen2 gen2refs
ON gen2grants.silverchair_id = gen2refs.silverchair_id
GROUP BY gen2grants.Silverchair_id
),
portfolio_cg_ids AS
(
SELECT DISTINCT md.silverchair_id
FROM
(
SELECT silverchair_id
FROM cg_cited_reference_gen1_grant gen1Grants
JOIN Appl_List appls
ON appls.core_proj_number = gen1Grants.ic_serial_num
UNION
SELECT silverchair_id
FROM cg_cited_reference_gen2_grant gen2Grants
JOIN Appl_List appls
ON appls.core_proj_number = gen2Grants.ic_serial_num
) grant_sc_ids
JOIN cg_metadata md
ON grant_sc_ids.silverchair_id = md.silverchair_id
)
SELECT
silverchairId,
TITLE,
PMID,
PMCID,
publication_year as year,
referenceCount1Gen,
supportingProjectCount1Gen,
supportedPublicationCount1Gen,
referenceCount2Gen,
supportingProjectCount2Gen,
supportedPublicationCount2Gen,
COUNT(1) OVER() as TotalCount
FROM
(
SELECT
md.SILVERCHAIR_ID silverchairId,
md.TITLE,
md.PMID,
md.PMCID ,
md.publication_year as year,
g1RefCounts.referenceCount1Gen as referenceCount1Gen,
g1SupportingProjCount.ApplCount as supportingProjectCount1Gen,
g1SupportedPubCount.PubCount as supportedPublicationCount1Gen,
g2RefCounts.referenceCount2Gen as referenceCount2Gen,
g2SupportingProjCount.ApplCount as supportingProjectCount2Gen,
g2SupportedPubCount.PubCount as supportedPublicationCount2Gen,
--COUNT(1) OVER() as TotalCount
FROM cg_metadata md
-- BEGIN datascope to current portfolio
JOIN portfolio_cg_ids
ON portfolio_cg_ids.silverchair_id = md.silverchair_id
-- END datascope to current portfolio
LEFT JOIN g1SupportingProjCount
ON g1SupportingProjCount.Silverchair_id = md.silverchair_id
LEFT JOIN g2SupportingProjCount
ON g2SupportingProjCount.Silverchair_id = md.silverchair_id
LEFT JOIN g1SupportedPubCount
ON g1SupportedPubCount.Silverchair_id = md.silverchair_id
LEFT JOIN g2SupportedPubCount
ON g2SupportedPubCount.Silverchair_id = md.silverchair_id
OUTER APPLY
(
Select Count(*) as referenceCount1Gen
FROM cg_cited_reference_gen1 g1Refs
WHERE g1Refs.silverchair_id = md.silverchair_id
) g1RefCounts
OUTER APPLY
(
Select Count(*) as referenceCount2Gen
FROM cg_cited_reference_gen2 g2Refs
WHERE g2Refs.silverchair_id = md.silverchair_id
) g2RefCounts
) results
ORDER BY {sortOrder}
Are there cases where some kind of special char in the string can keep this from working?
I'm kind of perplexed. I've been using this pattern for like 3 years and I've never had this not work.
What could be breaking this?
The query has 4000+ characters.
The text is probably being truncated somewhere down the line.