Relationship not defined with my pgsql Join - postgresql

I am new to this and haven't been able to find the proper syntax for my table join...
SELECT
DISTINCT on (date (billing.starttime))
medias.name,
date (billing.starttime),
Count(distinct (billing.starttime)) as "# Plays",
Count(distinct(billing.playerid)) as "# Stores"
FROM
public.billing,
public.medias
JOIN ????? on billing.mediaitemid = medias.id
WHERE
medias.name LIKE any (array['COMM_7032%']) and
billing.starttime >= date('2017-04-26') and
billing.starttime < date('2017-05-01')
GROUP BY
date (billing.starttime),
medias.name
ORDER BY
date (billing.starttime)
I am not sure what fits where the ????? are. Everything that I have tried states that the relationship does not exist.

It should go:
...
FROM
public.billing JOIN public.medias on billing.mediaitemid = medias.id
WHERE
...
the syntax is
[table1] join [table2] on [condition]

from
public.billing b
inner join
public.medias m on b.mediaitemid = m.id

Related

understanding the logic of AND and WHERE in t-sql

I am working on Transact-SQL, Microsoft Azure.
I am trying to understand why in some join queries WHERE and AND both can be used and give the same result (or at least it seemed like the same result in my data base) and in other queries where doesn't work and and does.
Here, I am joining 2 tables:
select c.customerID, ca.addressID, ca.addressType
from salesLT.customer as c
join salesLT.customerADdress as ca
on c.customerID = ca.customerID
WHERE ca.addressType = 'Main Office'; --WHERE or AND works the same
This gives me what I was looking for = only the rows from customerAddress table where the type is 'Main Office'. Changing the word WHERE to AND gives the exact same result.
Now, the query is based on the previous, but I am trying to join 3 tables. Here the WHERE doesn't work and I have to put an AND:
select c.customerId, c.companyName, ca.addressID, ca.addressType, a.addressLine1, a. city
from salesLT.customer as c
join salesLT.customerAddress as ca
on c.customerID = ca.customerID
WHERE ca.addressType = 'Main Office' -- error: incorrect syntax near 'join'
join salesLT.address as a
on ca.addressId = a.addressID;
If I change the WHERE to AND it works. Why? What is the difference between the join of 2 tables and 3?
Thanks
If I change the WHERE to AND it works. Why?
Because using and is adding the condition to the on clause, but using where is a new clause.
Here is the full explanation: The basic syntax of a select statement when using multiple joins is:
SELECT <columns>
FROM <table 1>
JOIN <table 2> ON <condition>
JOIN <table 3> ON <condition>
WHERE <condition>
This means your second query should look like this:
select c.customerId, c.companyName, ca.addressID, ca.addressType, a.addressLine1, a.city
from salesLT.customer as c
join salesLT.customerAddress as ca on c.customerID = ca.customerID
join salesLT.address as a on ca.addressId = a.addressID
WHERE ca.addressType = 'Main Office';
If you will go to the link, you will see that a select statement syntax can get much more complicated - but for now, that basic syntax should be enough to get you started.
The second JOIN should be before the WHERE clause
select c.customerId, c.companyName, ca.addressID, ca.addressType, a.addressLine1, a. city
from salesLT.customer as c
join salesLT.customerAddress as ca
on c.customerID = ca.customerID
join salesLT.address as a
on ca.addressId = a.addressID
WHERE ca.addressType = 'Main Office'
;

Lateral query syntax

I'm trying to get lateral to work in a Postgres 9.5.3 query.
select b_ci."IdOwner",
ci."MinimumPlaces",
ci."MaximumPlaces",
(select count(*) from "LNK_Stu_CI" lnk
where lnk."FK_CourseInstanceId" = b_ci."Id") as "EnrolledStudents",
from "Course" c
join "DBObjectBases" b_c on c."Id" = b_c."Id"
join "DBObjectBases" b_ci on b_ci."IdOwner" = b_c."Id"
join "CourseInstance" ci on ci."Id" = b_ci."Id",
lateral (select ci."MaximumPlaces" - "EnrolledStudents") x
I want the right-most column to be the result of "MaximumPlaces" - "EnrolledStudents" for that row but am struggling to get it to work. At the moment PG is complaining that "EnrolledStudents" does not exist - which is exactly the point of "lateral", isn't it?
select b_ci."IdOwner",
ci."MinimumPlaces",
ci."MaximumPlaces",
(select count(*) from "LNK_Stu_CI" lnk
where lnk."FK_CourseInstanceId" = b_ci."Id") as "EnrolledStudents",
lateral (select "MaximumPlaces" - "EnrolledStudents") as "x"
from "Course" c
join "DBObjectBases" b_c on c."Id" = b_c."Id"
join "DBObjectBases" b_ci on b_ci."IdOwner" = b_c."Id"
join "CourseInstance" ci on ci."Id" = b_ci."Id"
If I try inlining the lateral clause (shown above) in the select it gets upset too and gives me a syntax error - so where does it go?
Thanks,
Adam.
You are missing the point with LATERAL. It can access columns in tables in the FROM clause, but not aliases defined in SELECT clause.
If you want to access alias defined in SELECT clause, you need to add another query level, either using a subquery in FROM clause (AKA derived table) or using a CTE (Common Table Expression). As CTE in PostgreSQL acts as an optimization fence, I strongly recommend going with subquery in this case, like:
select
-- get all columns on the inner query
t.*,
-- get your new expression based on the ones defined in the inner query
t."MaximumPlaces" - t."EnrolledStudents" AS new_alias
from (
select b_ci."IdOwner",
ci."MinimumPlaces",
ci."MaximumPlaces",
(select count(*) from "LNK_Stu_CI" lnk
where lnk."FK_CourseInstanceId" = b_ci."Id") as "EnrolledStudents",
from "Course" c
join "DBObjectBases" b_c on c."Id" = b_c."Id"
join "DBObjectBases" b_ci on b_ci."IdOwner" = b_c."Id"
join "CourseInstance" ci on ci."Id" = b_ci."Id"
) t

how to solve this complicated sql query

these are the five given tables
http://i58.tinypic.com/53wcxe.jpg
this is the recomanded result
http://i58.tinypic.com/2vsrts7.jpg
please help how can i write a query to have this result.
no idea how!!!!
SELECT K.* , COUNT (A.Au_ID) AS AnzahlAuftr
FROM Kunde K
LEFT JOIN Auftrag A ON K.Kd_ID = A.Au_Kd_ID
GROUP BY K.Kd_ID,K.Kd_Firma,K.Kd_Strasse,K.Kd_PLZ,K.Kd_Ort
ORDER BY K.Kd_PLZ DESC;
SELECT COUNT (F.F_ID) AS AnzahlFahrt
FROM Fahrten F
RIGHT JOIN Auftrag A ON A.Au_ID = F.F_Au_ID
SELECT SUM (T.Ts_Strecke) AS SumStrecke
FROM Teilstrecke T
LEFT JOIN Fahrten F ON F.F_ID = T.Ts_F_ID
how to join these 3 in one?
Grouping on Strasse etc. is not necessary and can be quite expensive. What about this approach:
SELECT K.*, ISNULL(Au.AnzahlAuftr,0) AS AnzahlAuftr, ISNULL(Au.AnzahlFahrt,0) AS AnzahlFahrt, ISNULL(Au.SumStrecke,0) AS SumStrecke
FROM Kunde K
LEFT OUTER JOIN
(SELECT A.Au_Kd_ID, COUNT(*) AS AnzahlAuftr, SUM(Fa.AnzahlFahrt1) AS AnzahlFahrt, SUM(Fa.SumStrecke2) AS SumStrecke
FROM Auftrag A LEFT OUTER JOIN
(SELECT F.F_Au_ID, COUNT(*) AS AnzahlFahrt1, SUM(Ts.SumStrecke1) AS SumStrecke2
FROM Fahrten F LEFT OUTER JOIN
(SELECT T.Ts_F_ID, SUM(T.Ts_Strecke) AS SumStrecke1
FROM Teilstrecke T
GROUP BY T.Ts_F_ID) AS Ts
ON Ts.Ts_F_ID = F.F_ID
GROUP BY F.F_Au_ID) AS Fa
ON Fa.F_Au_ID = A.Au_ID
GROUP BY A.Au_Kd_ID) AS Au
ON Au.Au_Kd_ID = K.Kd_ID

Get maximum value of an aggregate function

I want to only return the row where the count(object) is the highest, so I have written this query
select klantnr, count(objectnaam)
from klanten inner join deelnames using(klantnr)
inner join reizen using(reisnr)
inner join bezoeken using(reisnr)
where objectnaam = 'Maan'
group by klantnr
Now, I can't do
select max(count(objectnaam))
How would I go about solving this problem?
I have tried by using a subquery which is equally invalid
select max(select count(objectnaam) from ....)
I think I need a subquery in the from, so I have rewritten the query like this which I think is closer to the actual answer but still not right, as now it returns the maximum value of all rows.
select klantnr, max(c)
FROM(
select klantnr, count(objectnaam) as c
from klanten inner join deelnames using(klantnr)
inner join reizen using(reisnr)
inner join bezoeken using(reisnr)
where objectnaam = 'Maan'
group by klantnr) as F
group by klantnr
thanks for any help you can give me!
You do not provide the structure of tables, so probably you have to modify the following query. However it works just for PostgreSQL 9.x+
WITH t AS (
SELECT klantnr, COUNT(objectnaam) AS c
FROM klanten
WHERE objectnaam = 'Maan'
GROUP BY klantnr
ORDER BY c DESC
LIMIT 1
)
SELECT * FROM t
INNER JOIN deelnames USING(klantnr)
INNER JOIN reizen USING(reisnr)
INNER JOIN bezoeken USING(reisnr);
see http://www.postgresql.org/docs/9.3/static/queries-with.html how to use WITH QUERIES.
I have found a simpeler solution:
select klantnr,count (klantnr)
from bezoeken natural join deelnames
where objectnaam ='Maan'
group by klantnr
order by count desc
limit 1

The multi-part identifier "t.PartNumber" could not be bound - with union

I need the records from TableMain which have a record match in ActivePNs and also a match in [Parts]. It seems that a join should do the trick but I keep running up against either a "could not be bound" or a "invalid column name" error.
I'm sure I could accomplish what I need by creating a temp table, but I'm trying to keep it simple.
Select * from TableMain t
INNER JOIN (select [PartNumber]
From ActivePNs ap
Where ap.PartNumber = t.PartNumber
Union
select [Number] PartNumber
From [Parts] p
Where p.Number = t.PartNumber) c
On t.PartNumber = c.PartNumber
Assuming there aren't multiple rows in ActivePNs or Parts for a given PartNumber, then from what I've understood, this should do the trick - only finding rows in TableMain that have a PartNumber in ActivePNs and Parts:
Select t.*
from TableMain t
INNER JOIN ActivePNs ap ON t.PartNumber = ap.PartNumber
INNER JOIN Parts p ON t.PartNumber = p.Number
Your problem is in the SELECT after the UNION.
select [Number] PartNumber -- You rename Number to PartNumber
From [Parts] p
Where p.Number = t.PartNumber -- but still reference Number here
The aliasing of Number in the SELECT means there's no column p.Number for use in the WHERE portion of the query.
A derived table cannot be correlated with the tables it is being joined to. What you are trying to do could be implemented like this:
SELECT
t.*,
COALESCE(ap.PartNumber, p.Number) AS PartNumber
FROM TableMain t
LEFT JOIN ActivePN ap ON ap.PartNumber = t.PartNumber
LEFT JOIN Parts p ON p.Number = t.PartNumber
WHERE NOT (ap.PartNumber IS NULL AND p.Number IS NULL)