SQL same postal code - sql

select PERSON.fornavn, PERSON.efternavn, PERSON.postnr, POST.distrikt
from PERSON inner join POST on POST.postnr = PERSON.postnr
inner join MEDLEM on PERSON.personnr = MEDLEM.personnr
inner join FORMAND on MEDLEM.personnr = FORMAND.personnr
group by PERSON.fornavn, PERSON.efternavn, PERSON.postnr, POST.distrikt, FORMAND.afdnr
having FORMAND.afdnr = 3
order by PERSON.fornavn
I need to show the persons that live on the same postal code as the boss for department 3, but the results make no sense.
Fornavn = First name, Formand = boss, Adresse = adress, Afdeling = Department (afdnr = department nr.), Medlem = member
Tables:
PERSON: personnr, fornavn, adresse, postnr
POST: postnr, district
FORMAND: personnr, afdnr
MEDLEM: personnr, afdnr
AFDELING: afdnr, afdname

select PERSON.fornavn, PERSON.efternavn, PERSON.postnr, POST.distrikt
from PERSON inner join POST on POST.postnr = PERSON.postnr
inner join MEDLEM on PERSON.personnr = MEDLEM.personnr
inner join FORMAND on MEDLEM.personnr = FORMAND.personnr
where FORMAND.afdnr = 3
group by PERSON.fornavn, PERSON.efternavn, PERSON.postnr, POST.distrikt, FORMAND.afdnr
order by PERSON.fornavn
try with :
where FORMAND.afdnr = 3
insteed of
having FORMAND.afdnr = 3

If I understand you right ("the persons that live on the same postal code as (the boss for department 3)", and assuming there is only one boss:
select PERSON.fornavn, PERSON.efternavn, PERSON.postnr, POST.distrikt
from PERSON
inner join POST on POST.postnr = PERSON.postnr
where PERSON.postnr = (SELECT pf.postnr
FROM FORMAND f
inner join PERSON pf ON f.personnr = pf.personnr
WHERE f.afdnr = 3)
order by PERSON.fornavn
Note: Your query makes no sense given the description, unless I am missing something. You are joining PERSON through MEDLEM to FORMAND on personnr, which means you will only get the boss's record back (PERSON.personnr = FORMAND.personnr).
Note: If there is more than one boss, you can change the = in the WHERE clause to IN to get all people that live in the same post code as any of the bosses.
In case I read you wrong, and you actually mean "the (persons that live on the same postal code as the boss) for department 3", try:
select p.fornavn, p.efternavn, p.postnr, POST.distrikt
from PERSON p
inner join POST on POST.postnr = p.postnr
inner join MEDLEM on p.personnr = MEDLEM.personnr
inner join FORMAND on MEDLEM.afdnr = FORMAND.afdnr
inner join PERSON pf on FORMAND.personnr = pf.personnr AND pf.postnr = p.postnr
where MEDLEM.afdnr = 3
order by PERSON.fornavn
Note: Again, I believe your join from the question is strange. See above.

Related

SQL query with multiple where clause

I'm trying to write a query for a dataset in SSRS. I have a joining table called RequestSchools which links to three other tables:
Schools
Placing Request
RequestSchoolType
I want to get the name of the RequestedSchool (RequestedSchoolTypeId = 3)
I also want the name of the CatchmentSchool (RequestSchoolTypeId = 1)
I've attached an image of the SQL query that I can get working with the requested school. I want the catchment school as well. Grateful for any help with this.
SELECT
pr.PlacingRequestId, s.Name AS RequestedSchool
FROM
PlacingRequests AS pr
INNER JOIN
RequestSchools AS rs ON rs.PlacingRequestId = pr.PlacingRequestId
JOIN
Schools s ON s.SchoolId = rs.SchoolId
WHERE
rs.RequestSchoolTypeId = 3
I'm not 100% sure this is correct, as we can't see the schema, source data or a full example of the desired output, but I think this might be it:
SELECT
pr.PlacingRequestId,
s.Name as RequestedSchool,
cs.Name as CatchmentSchool
FROM
PlacingRequests AS pr
INNER JOIN RequestSchools AS rs
ON rs.PlacingRequestId = pr.PlacingRequestId
INNER JOIN Schools s
on s.SchoolId = rs.SchoolId
AND rs.RequestSchoolTypeId = 3 -- requested school
INNER JOIN Schools cs
on cs.SchoolId = rs.SchoolId
AND rs.RequestSchoolTypeId = 1 -- catchment school
Happy to update if it's not what you meant, and you can clarify the question as indicated.
According what I understand about your requirement, you will be needing multiple joins and not another AND condition in the where clause. So we can omit the where here and join the requestschools with schools one more time for CatchmentSchool as we have done it once already for Requestedschool. Only difference is we are using the requestedtypeid and catchmenttypeid values while joining.
Select
pr.PlacingRequestId,
rs.Name as RequestedSchool
cs.Name as CatchmentSchool
FROM
PlacingRequests AS pr
INNER JOIN RequestSchools AS rrs
ON rrs.PlacingRequestId = pr.PlacingRequestId
and rrs.RequestSchoolTypeId = 3
JOIN Schools rs
on rs.SchoolId = rrs.SchoolId
INNER JOIN RequestSchools AS crs
ON crs.PlacingRequestId = pr.PlacingRequestId
and crs.RequestSchoolTypeId = 1
JOIN Schools cs
on cs.SchoolId = crs.SchoolId
Hope this helps...
The best way to do this is with a CASE function, but I don't know which RDBMS you are using so here is the brute force approach: just run your query as two sub-queries, each specifying a different type ID and then join them. It would be something like this:
SELECT DISTINCT catch.placingrequestid, catch.catchmentschool, requested.requestedschool
FROM
(SELECT pr.placingrequestid, s.nam as catchmentschool
FROM (PlacingRequest pr
INNER JOIN RequestSchools rs ON pr.placingrequestid = rs.placingrequestid)
INNER JOIN School s ON rs.schoolid = s.schoolid
WHERE rs.requestschooltypeid = 1) catch
INNER JOIN
(SELECT pr.placingrequestid, s.nam as requestedschool
FROM (PlacingRequest pr
INNER JOIN RequestSchools rs ON pr.placingrequestid = rs.placingrequestid)
INNER JOIN School s ON rs.schoolid = s.schoolid
WHERE rs.requestschooltypeid = 3) requested
ON catch.placingrequestid = requested.placingrequestid

Oracle Error-ORA-00933: SQL command not properly ended

I cannot figure out why I am getting this error message....
SELECT student.student, course.coursename, course.coursehours, section.day, section.starttime, course.building, location.room
FROM student, course, section, location, registration
WHERE course.courseid = section.courseid, location.locationid =
section.locationid, student.studentid = registration.sectionid,
section.sectionid = registration.sectionid;
Error at line 3:
ORA-00933: SQL command not properly ended
I updated my data to look like this:
SELECT student.studentid,
course.coursename,
course.credithours,
section.days,
section.starttime,
location.building,
location.room
FROM student
INNER JOIN registration
ON student.studentid = registration.sectionid
INNER JOIN section
ON section.sectionid = registration.sectionid
INNER JOIN location
ON location.locationid = section.locationid
INNER JOIN course
ON course.courseid = section.courseid;
but now it is saying "no rows selected"?
When you have more than one condition you need to use AND/OR operator to apply the condition not comma. Also start using INNER JOIN syntax
SELECT student.student,
course.coursename,
course.coursehours,
section.day,
section.starttime,
course.building,
location.room
FROM student
INNER JOIN registration
ON student.studentid = registration.sectionid
INNER JOIN section
ON section.sectionid = registration.sectionid
INNER JOIN location
ON location.locationid = section.locationid
INNER JOIN course
ON course.courseid = section.courseid

SQL update statement inserting PeopleID into child tables to link data

I need to place the PeopleID in several tables for my new database to link all of the peole information. I have tried several times to write a simple update statement please help. Every time I get close I get AMBIGUOUS COLUMN ERROR I don't know what else to do.
Update CONTRACT
Set PeopleID = B.PeopleID
from People A
Inner join
(
Select PeopleId, F.ContractID
From People A
Inner Join Person PRSN on PRSN.PersonID = A.PersonID
Inner Join DARPA_IMPORT_REAL..persnl oldP on oldP.pl_pid = PRSN.PersonID
Left outer join Contract F on F.ContractID = oldP.kn_254id
) B on A.PeopleID = B.PeopleID
Go
try this
Update CONTRACT Set CONTRACT.PeopleID = B.PeopleID
from People A
Inner join (
Select A.PeopleId, F.ContractID
From People AA
Inner Join Person PRSN on PRSN.PersonID = AA.PersonID
Inner Join DARPA_IMPORT_REAL..persnl oldP on oldP.pl_pid = PRSN.PersonID
Left outer join Contract F on F.ContractID = oldP.kn_254id ) B
on A.PeopleID = B.PeopleID
you were asigning the ´A´ alias twice so I recomend using different aliases always

OJB ReportQuery join question

Given three tables:
People: {Person_Id, Age}
Accounts: {Account_Id, Person_Id, Account_Type}
Age_Ranges: {Age_Range_Id, Age_Range_Label, Lower_Bound, Upper_Bound}
I'm trying to represent the following SQL query using OJB (without resorting to a QueryBySQL):
select ar.Age_Range_Label, count(a.Account_Id)
from People p
inner join Accounts a on p.Person_Id = a.Person_Id
inner join Age_Ranges ar on p.Age between ar.Lower_bound and ar.Upper_Bound
where a.Account_Type = 'Chequing'
The java code I have so far looks like this:
Criteria criteria = new Criteria();
criteria.addEqualTo("Account_Type", "Chequing");
// join on Age_Ranges based on the person's Age
criteria.???
ReportQueryByCriteria q = QueryFactory.newReportQuery(Accounts.class, criteria);
q.setAttributes(new String[] {"Age_Range_Label", "count(Account_Id)"});
q.addGroupBy("Age_Range_Label");
...
But I'm unsure how to join up with the Age_Ranges table such that I can group on the Age_Range_Label column.
Any insight?

Sql Outer Join: Extracting values from multible tables

I am extracting data from multiple tables. mt query is as follows:
SELECT p.Record_Num as RecordNum
,p.GCD_ID as GCDID
,p.Project_Desc as ProjectDesc
,p.Proponent_Name as ProponentName
,st.Station_Name as StationName
,p.OpCentre as OpCentre
,s.Sector_Name as SectorName
,p.PLZone as PLZone
,f.Feeder_Desc as FeederDesc
,d.DxTx_Desc as DxTx
,op.Op_Control_Desc as OpControl
,t.Type_Desc as Type
,c.Conn_Desc as ConnectionKV
,ss.Status_Desc as Status
,p.MW as MW
,p.Subject as Subject
,p.Ip_Num as IpNum
,p.H1N_ID as H1NID
,p.NOMS_Slip_Num as NomsSlipNum
,p.NMS_Updated as NmsUpdated
,p.Received_Date as ReceivedDate
,p.Actual_IS_Date as ActualISDate
,p.Scheduled_IS_Date as ScheduledIsDate
,stst.Station_Name as UpStation
,ff.Feeder_Desc as UpFeeder
,p.HV_Circuit as HVCircuit
,p.SIA_Required as SIAReqd
FROM Project_Detail p,
Station st, Sector s, Feeder f, DxTx d, Operational_Control op, Type t,
Connection_Kv c, Status ss, Station stst, Feeder ff
WHERE
p.Station_ID = st.Station_ID and
p.Sector_ID = s.Sector_ID and
p.Feeder = f.Feeder_ID and
p.DxTx_ID = d.DxTx_ID and
p.OpControl_ID = op.Op_Control_ID and
p.Type_ID= t.Type_ID and
p.ConnKV_ID = c.Conn_ID and
p.Status_ID = ss.Status_ID and
p.UP_Station_ID = stst.Station_ID and
p.UP_Feeder_ID = ff.Feeder_ID
The problem with this query is if it doesnot find an associated value in the second table, it doesnot show the row.
for example : every project has feeders. so if a project_detail table has a feederid which doesnot have an association in the feeder table, then it wont show the row. also, there are times when the feeders are not assigned to a project.
i think i have to use outer joins to get the values. but i cannot figure out how to do that.
please help.
SELECT *
FROM Project_Detail p
LEFT JOIN
Station st
ON p.Station_ID = st.Station_ID
LEFT JOIN
Sector s
ON p.Sector_ID = s.Sector_ID
…
You need LEFT OR FULL OUTER JOINS instead of the inner joins you are now using with your where clause.
SELECT p.Record_Num as RecordNum
,p.GCD_ID as GCDID
,p.Project_Desc as ProjectDesc
,p.Proponent_Name as ProponentName
,st.Station_Name as StationName
,p.OpCentre as OpCentre
,s.Sector_Name as SectorName
,p.PLZone as PLZone
,f.Feeder_Desc as FeederDesc
,d.DxTx_Desc as DxTx
,op.Op_Control_Desc as OpControl
,t.Type_Desc as Type
,c.Conn_Desc as ConnectionKV
,ss.Status_Desc as Status
,p.MW as MW
,p.Subject as Subject
,p.Ip_Num as IpNum
,p.H1N_ID as H1NID
,p.NOMS_Slip_Num as NomsSlipNum
,p.NMS_Updated as NmsUpdated
,p.Received_Date as ReceivedDate
,p.Actual_IS_Date as ActualISDate
,p.Scheduled_IS_Date as ScheduledIsDate
,stst.Station_Name as UpStation
,ff.Feeder_Desc as UpFeeder
,p.HV_Circuit as HVCircuit
,p.SIA_Required as SIAReqd
FROM Project_Detail p
LEFT OUTER JOIN Station st ON p.Station_ID = st.Station_ID
LEFT OUTER JOIN Sector s ON p.Sector_ID = s.Sector_ID
LEFT OUTER JOIN Feeder f ON p.Feeder = f.Feeder_ID
LEFT OUTER JOIN DxTx d ON p.DxTx_ID = d.DxTx_ID
LEFT OUTER JOIN Operational_Control op ON p.OpControl_ID = op.Op_Control_ID
LEFT OUTER JOIN Type t ON p.Type_ID= t.Type_ID
LEFT OUTER JOIN Connection_Kv c ON p.ConnKV_ID = c.Conn_ID
LEFT OUTER JOIN Status ss ON p.Status_ID = ss.Status_ID
LEFT OUTER JOIN Station stst ON p.UP_Station_ID = stst.Station_ID
LEFT OUTER JOIN Feeder ff ON p.UP_Feeder_ID = ff.Feeder_ID