Subquery with inner join - postgresql

SELECT c.first_name, c.last_name
FROM customer c
INNER JOIN payment p ON C.CUSTOMER_ID = p.customer_id
WHERE p.amount > (SELECT AVG(amount) FROM payment)
INNER JOIN city ON city_id = c.city.city_id
WHERE c.city LIKE '%a%'
ERROR: syntax error at or near "INNER"
LINE 6: INNER JOIN city
^
SQL state: 42601
Character: 155

Second "INNER JOIN" must be before "WHERE"
SELECT
c.first_name,
c.last_name
FROM customer c
INNER JOIN payment p ON (p.customer_id = c.CUSTOMER_ID)
INNER JOIN city ON (city.city_id = c.city_id)
WHERE
p.amount > (SELECT AVG(amount) FROM payment)
AND city.city LIKE '%a%'

Related

Recursive select in Postgres SQL

I'm trying to make my first recursive query in SQL and get an unxpected syntax error with inner join clause. I don't understand what causes this error. The query is simple it is just to select all employee attached to their boss with simple rule: BOSS_POS_ID = POS_ID
Here is example of my data:
POS_ID;POS_NAME;BOSS_POS_ID
32520602;CEO;
32809988;Manager;32520602
35244656;Vice;32520602
35244652;CEO assistant;32520602
35042934;Manager;32520602
35255704;Manager;32520602
35342468;Director;32520602
34091164;Director;32520602
35236439;Excecutive;32520602
32809978;Director;32520602
Here is my query:
with recursive subordinates as
(
select POS_ID, POS_NAME, BOSS_POS_ID
from gdm.hr_oss
where
POS_ID = 32520602
and CAL_DAY = (select max(CAL_DAY) from gdm.hr_oss)
union select
e.POS_ID,
e.POS_NAME,
e.BOSS_POS_ID
from gdm.hr_oss e
where CAL_DAY = (select max(CAL_DAY) from gdm.hr_oss)
inner join subordinates s on s.POS_ID = e.BOSS_POS_ID
)
select * from subordinates;
Here is error:
ERROR. Execution failed on sql '
with recursive subordinates as
(
select POS_ID, POS_NAME, BOSS_POS_ID
from gdm.hr_oss
where
POS_ID = 32520602
and CAL_DAY = (select max(CAL_DAY) from gdm.hr_oss)
union select
e.POS_ID,
e.POS_NAME,
e.BOSS_POS_ID
from gdm.hr_oss e
where CAL_DAY = (select max(CAL_DAY) from gdm.hr_oss)
inner join subordinates s on s.POS_ID = e.BOSS_POS_ID
)
select * from subordinates;
': syntax error at or near "inner"
LINE 15: inner join subordinates s on s.POS_ID = e.BOSS_POS_ID

postgres error 42803 with subquery and group by

Hi all postgres developer,
below code can run success
select p.* from
(select p.*, count(distinct p1.id) n from TMB p
left join TMB p1 on p.id = p1.pid
left join TUR u on p.id = any(u.jks)
group by p.id) p
join TUR u on u.id = p.uid
but, below code with error message
[42803] ERROR: column "p.xxxx" must appear in the GROUP BY clause or be used in an aggregate function
select p.* from
(select p.*, count(distinct p1.id) n from (select * from TMB) p
left join TMB p1 on p.id = p1.pid
left join TUR u on p.id = any(u.jks)
group by p.id) p
join TUR u on u.id = p.uid
I want to do some where filter on TMB table before left join, so I think can speed up left join.
I think (select * from TMB) is a subquery equal as TMB. I can not understand why this error message. anyone can tell me detail?
The difference is that without the subquery, PostgreSQL can deduce that id is the primary key of tmb, so you need not add all columns of tmb to the GROUP BY clause. With the subquery, PostgreSQL cannot make that deduction, so you have to add all columns.

Problems with Postgresql ERROR: subquery uses ungrouped column "ev.title" from outer query

I have a query like this:
select c.id, c.name, c.website, c.longdescription, c.description, c.email,
(SELECT jsonb_agg(ev) FROM
(SELECT ev.title, ev.description, ev.longdescription,
(SELECT jsonb_agg(ed) FROM
(SELECT ed.startdate, ed.enddate, ed.id WHERE ed.id notnull)ed) as dates, ev.id WHERE ev.id notnull) ev) as events,
(SELECT jsonb_agg(ca) FROM (SELECT ct.zip, ca.id, ca.street1, ca.street2, ca.addresstype_id, ST_Y(ca.geopoint::geometry) as latitude, ST_X(ca.geopoint::geometry) as longitude
WHERE ca.id notnull)ca) as addresses
FROM companies c
LEFT JOIN events ev ON ev.company_id = c.id
LEFT JOIN companyaddresses ca ON ca.company_id = c.id
LEFT JOIN cities ct ON ct.id = ca.city_id
LEFT JOIN eventdates ed ON ed.event_id = ev.id
GROUP by c.id
I am getting the error "ERROR: subquery uses ungrouped column "ev.title" from
outer query Position: 125".
Can't figure out how to group it correctly for the subqueries. Any suggestions?
Give this a try:
SELECT c.id, c.name, c.website, c.longdescription, c.description, c.email,
    (SELECT jsonb_agg(ev) FROM
        (SELECT even.title, even.description, even.longdescription,
            (SELECT jsonb_agg(ed) FROM
                (SELECT eventdates.startdate, eventdates.enddate, eventdates.id FROM eventdates WHERE eventdates.event_id = even.id)ed) as dates,
        even.id FROM events even WHERE even.company_id = c.id) ev) as events,
jsonb_agg((SELECT ca FROM (SELECT ct.zip, ca.id, ca.street1, ca.street2, ca.addresstype_id, ST_Y(ca.geopoint::geometry) as latitude, ST_X(ca.geopoint::geometry) as longitude WHERE ca.id notnull)ca)) as addresses
FROM companies c
LEFT JOIN companyaddresses ca ON ca.company_id = c.id
LEFT JOIN cities ct ON ct.id = ca.city_id
Group by c.id

Bad performance for muli joined sub-queries

Could someone help me on this query. When generating the related report through web application it times out due to response time taking over 30seconds(standard http request time out).
select c.counterparty_shortname AS [Réference]
,cty.counterparty_type_name AS [Type ref]
,t.transaction_shortname AS [transaction_shortname]
,mitigant_shortname
,(SELECT ISNULL(SUM(ISNULL(tce.outstanding_amount,0)),0)
from transaction_credit_event tce
where tce.transaction_id=t.transaction_id) AS [Montant impayé]
,(select count(t1.transaction_id)
from [transaction] t1
where t1.counterparty_id=c.counterparty_id) AS [Nbre affaire]
,(select isnull(count(tce.credit_event_id),0)
from transaction_credit_event tce
where tce.transaction_id=t.transaction_id
and isnull(tce.outstanding_amount,0)>0
and tce.credit_event_type_id=51) AS [nbr impaye]
,TT.transaction_type_name AS [Type Produit]
,isnull(cm1.value1_text,'') AS [type garantie]
,isnull(cm2.value1_text,'') AS [marque]
,isnull(cm3.value1_text,'') AS [modele]
,(select top 1 tmp1.payment_posting_date
from (select pp.payment_posting_date
,tce.transaction_id
FROM payment_posting pp
inner JOIN transaction_credit_event tce
ON pp.credit_event_id=tce.credit_event_id) tmp1
where tmp1.transaction_id=t.transaction_id
order by tmp1.payment_posting_date desc) AS [Date dernier paiement]
,fate_shortname AS [sort]
,raf.recovery_action_fate_id
,ISNULL(t.outstanding_amount,0) AS [CRD]
,1 AS [ID]
,(select isnull(count(tce.credit_event_id),0)
from transaction_credit_event tce,[transaction] tt
where tce.transaction_id=tt.transaction_id
and tt.counterparty_id=c.counterparty_id
and isnull(tce.outstanding_amount,0)>0
and tce.credit_event_type_id=51) AS [nbr impaye tiers]
,convert(date,dispatch_start_date,103) AS [date debut]
,convert(date,dispatch_end_date,103) AS [date fin]
,c.counterparty_type_id
,t.transaction_type_id
from counterparty c
inner join wf_task_dispatch w on w.item_id=c.counterparty_id
inner join [transaction] t on c.counterparty_id=t.counterparty_id
LEFT join transaction_recovery tr on tr.counterparty_id=c.counterparty_id and tr.transaction_recovery_id=(select top 1 transaction_recovery_id from transaction_recovery where counterparty_id=c.counterparty_id order by idate desc)
LEFT join recovery_action_fate raf on raf.recovery_action_fate_id=tr.recovery_action_fate_id
left join counterparty_type cty on cty.counterparty_type_id=c.counterparty_type_id
left join [transaction_type] TT on t.transaction_type_id = TT.transaction_type_id
inner join mitigant_transaction mt on mt.transaction_id=t.transaction_id and mt.ddate is null
inner join mitigant m on m.mitigant_id=mt.mitigant_id and mitigant_screen='asset' and m.ddate is null
left join constant_matrix cm1 on cm1.criteria1_text=m.regulatory_mitigant_type and cm1.constant_matrix_shortname='CAIN' and cm1.ddate is null
left join constant_matrix cm2 on cm2.criteria1_text=m.valuation_frequency and cm2.constant_matrix_shortname='MARQ' and cm2.ddate is null
left join constant_matrix cm3 on cm3.criteria1_text=m.valuation_source and cm3.constant_matrix_shortname='GMOD' and cm3.ddate is null
where (select [dbo].FN_GetPhase)=81

How to aggregate calculation in SQL Server?

I have a following script to get the total unit but it gives me an error
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
Do I need to calculate SUM(ta.Qty) outside the main table?
SELECT
ta.ProductName
, SUM(ta.Total)
, SUM(SUM(ta.Qty) * ta.Unit)
FROM
tableA tA
INNER JOIN
tableB tB on tA.ID = tb.TableAID
INNER JOIN
tableC tc on ta.ID = tc.TableAID
INNER JOIN
tableD td on td.ID = tb.TableBID
GROUP BY
ta.ProductName
Here is a query in the AdventureWorks database that produces the same error (but might make some sense):
SELECT v.Name AS Vendor, SUM(SUM(p.ListPrice*d.OrderQty)+h.Freight)
FROM Production.Product p
INNER JOIN Purchasing.PurchaseOrderDetail d ON p.ProductID = d.ProductID
INNER JOIN Purchasing.PurchaseOrderHeader h ON h.PurchaseOrderID = d.PurchaseOrderID
INNER JOIN Purchasing.Vendor v ON v.BusinessEntityID = h.VendorID
GROUP BY v.Name
And here are two ways that I could rewrite that query to avoid the error:
SELECT v.Name AS Vendor, SUM(x.TotalAmount+h.Freight)
FROM (
SELECT PurchaseOrderID, SUM(p.ListPrice*d.OrderQty) AS TotalAmount
FROM Production.Product p
INNER JOIN Purchasing.PurchaseOrderDetail d ON p.ProductID = d.ProductID
GROUP BY PurchaseOrderID
) x
INNER JOIN Purchasing.PurchaseOrderHeader h ON h.PurchaseOrderID = x.PurchaseOrderID
INNER JOIN Purchasing.Vendor v ON v.BusinessEntityID = h.VendorID
GROUP BY v.Name
SELECT v.Name AS Vendor, SUM(x.TotalAmount+h.Freight)
FROM Purchasing.PurchaseOrderHeader h
INNER JOIN Purchasing.Vendor v ON v.BusinessEntityID = h.VendorID
CROSS APPLY (
SELECT SUM(p.ListPrice*d.OrderQty) AS TotalAmount
FROM Production.Product p
INNER JOIN Purchasing.PurchaseOrderDetail d ON p.ProductID = d.ProductID
WHERE d.PurchaseOrderID=h.PurchaseOrderID
) x
GROUP BY v.Name
The first query uses derived tables and the second one uses CROSS APPLY.