SQL joining three tables and selecting information - sql

I have 3 tables
Doctor - Staff_ID, Name, Position.
Consists_Of - Staff_Id, Team_Code.
Team - Team_Code, Telephone_No, Staff_ID
The team table consists of the team leader for each team who is also a doctor,
I need to return a table that has team_code, staff_Id, name, position
I have got
SELECT DISTINCT Team.team_code, Doctor.staff_ID, name, position
FROM Doctor, Team LEFT OUTER JOIN consists_of
ON Team.Team_code = consists_of.Team_code
But this is giving every each member of stay the team code, t1 and then t2 and then t3 and so on.
Any ideas?

What you need is use JOIN. The repetition occurred because you didn't specify on what field should Doctor and Team be joined
SELECT Team.team_code, Doctor.staff_ID, name, position
FROM Doctor
LEFT OUTER JOIN consists_of
ON Doctor.Staff_Id=consists_of.Staff_Id
LEFT OUTER JOIN Team
ON Team.Team_code = consists_of.Team_code
But why do you have Staff_Id in Team table?

Related

PostgreSQL JOIN in aggregate function

Treatment table schema
id
doctor_id
location_id
patient_id
...
I need to be able to group patient treatments based on location and list all the doctors that were treating the patient for the specific location.
SELECT id,
(SELECT STRING_AGG(t.initials::text, ',') FROM (
SELECT DISTINCT treatments.doctor_id, doctors.initials FROM
treatments LEFT JOIN doctors ON doctors.id = treatments.doctor_id) t
) as treating_doctors_initials
GROUP BY treatments.patient_id, treatments.location_id
The problem is that this returns the same initials for all records -> it does perform the join I guess or maybe I am misunderstanding the aggregate function.

INNER JOIN and Count POSTGRESQL

I am learning postgresql and Inner join I have following table.
Employee
Id Name DepartmentId
1 John S. 1
2 Smith P. 1
3 Anil K. 2
Department
Department
Id Name
1 HR
2 Admin
I want to query to return the Department Name and numbers of employee in each department.
SELECT Department.name , COUNT(Employee.id) FROM Department INNER JOIN Employee ON Department.Id = Employee.DepartmentId Group BY Employee.department_id;
I dont know what I did wrong as I am new to database Query.
When involving all rows or major parts of the "many" table, it's typically faster to aggregate first and join later. Certainly the case here, since we are after counts for "each department", and there is no WHERE clause at all.
SELECT d.name, COALESCE(e.ct, 0) AS nr_employees
FROM department d
LEFT JOIN (
SELECT department_id AS id, count(*) AS ct
FROM employee
GROUP BY department_id
) e USING (id);
Also made it a LEFT [OUTER] JOIN, to keep departments without any employees in the result. And COALESCE to report 0 employees instead of NULL in that case.
Related, with more explanation:
Query with LEFT JOIN not returning rows for count of 0
Your original query would work too, after fixing the GROUP BY clause:
SELECT department.name, COUNT(employee.id)
FROM department
INNER JOIN employee ON department.id = employee.department_id
Group BY department.id; --!
That's assuming department.id is the PRIMARY KEY of the table, in which case it covers all columns of that table, including department.name. And you may want LEFT JOIN like above.
Aside: Consider legal, lower-case names exclusively in Postgres. See:
Are PostgreSQL column names case-sensitive?

Microsoft SMSS - Joining tables on t2.primary key = t1.foreign_key

I need to join two tables together to create a table with columns for employee id, employee name and their boss' name.
The 'hier' table
The 'employees' table
The query I wrote is almost working, putting an employee name in the right spot, but not the right employee:
SELECT em.emp_id, em.emp_name, em.emp_name AS boss_name
FROM employees em
LEFT JOIN hier h ON (h.boss_id = em.emp_name)
Which outputs:
I need to have each person's boss to have the right name, and in the case of Big Boss, 'N/A'. Like so:
You need a self join with Employee table
SELECT em.emp_id, em.emp_name, e1.emp_name AS boss_name
FROM employees em
LEFT JOIN employees em1 ON em.boss_id = em1.emp_id

Query to select related data from two tables in which one table has no related fields in third table

I have three tables in my Oracle db:
Peoples:
IdPerson PK
Name
Surname
Earnings:
IdEarning PK
IdPerson
EarningValue
Awards:
IdAward PK
IdPerson FK
AwardDescription
So one person can have many earnings, one earning or can have no any earnings. Also one person can have many awards, one award, or no any award.
I have to select Surname and AwardDescription but only for people who have any earnings, because it is possible to have some award but, also don't have any earning!
My problem is to make a correct group by statement. I use query posted below and I am selecting surname of person with a description of award, but it is duplicating for each row in Earnings for this person.
SELECT AwardDescription, Surname
FROM Awards
INNER JOIN People ON People.IdPerson= Awards.IdPerson
INNER JOIN Earnings ON Earnings .IdPerson= People.IdPerson;
How to group it and avoid duplicating rows for each earning of person?
One person can be in many rows, but with different awards.
You could add DISTINCT to your query:
SELECT DISTINCT AwardDescription, Surname
FROM Awards
INNER JOIN People ON People.IdPerson= Awards.IdPerson
INNER JOIN Earnings ON Earnings .IdPerson= People.IdPerson;
Or another option is to use EXISTS:
SELECT AwardDescription, Surname
FROM Awards
INNER JOIN People P ON P.IdPerson= Awards.IdPerson
WHERE EXISTS (
SELECT 1
FROM Earnings E
WHERE P.IdPerson = E.IdPerson);
Do a left outer join among the tables like
SELECT p.Surname, a.AwardDescription, e.EarningValue
FROM People p
LEFT JOIN Awards a ON p.IdPerson= a.IdPerson
LEFT JOIN Earnings e ON e.IdPerson= p.IdPerson
WHERE a.AwardDescription IS NOT NULL
OR e.EarningValue IS NOT NULL;

SQL Join Issue with Nulls

I have 7 tables I am using in a view. For examples, I will be using these as my table names (The Fields within the table don't matter for this execpt that the PrimaryKey is tableName + ID)
Table 1.
Teacher
Table 2.
Student (Exception-- Student has all the ids in it, from all the other 6 tables)
Table 3.
Science
Table 4.
Math
Table 5.
History
Table 6.
German
Table 7.
Language Arts
Now, All the tables from 3-7 have a relationship to Student from Table 2. And Student has a relationship to teacher.
My view currently works if any of my tables have any fields. and some can be null, it also works if any of my tables 3-7 are completely null, it will still display.
However, my current problem is, if my teacher has no students assigned to them, making tables 2-7 null, empty, etc.... My query doesnt even return the teacher info that is filled in... First name, last name, Date of birth, etc.
How can I Accomplish this?
I tried doing all left joins from all the tables, since the teacher can have null fields, I tried doing an inner join from dbo.Teacher as Teacher Inner Join dbo.Student on dbo.Student.TeacherID = Teacher.TeacherID but that didnt work.. I am at a loss...
SELECT Teacher.TeacherID ,
Student.StudentID ,
Science.ScienceID ,
History.HistoryID ,
Math.MathID ,
German.GermanID ,
LanguageArts.LanguageArtsID
FROM dbo.Teacher AS Teacher
LEFT OUTER JOIN dbo.Student
ON dbo.Student.TeacherID = Teacher.TeacherID
LEFT OUTER JOIN dbo.Science AS Science
ON dbo.Student.ScienceID = Science.ScieneID
LEFT OUTER JOIN dbo.Math AS Math
ON dbo.Student.MathID = Math.MathID
LEFT OUTER JOIN dbo.History AS History
ON dboStudent.HistoryID = History.HistoryID
LEFT OUTER JOIN dbo.German AS German
ON dbo.Student.GermanID = German.GermanID
LEFT OUTER JOIN dbo.LanuageArts AS LanguageArts
ON dbo.Student.LanguageArtsID = LanguageArts.LanguageArtsID
Two comments:
Do you know the use of LEFT JOIN?. This query should return all teachers, even thouse with no students.
SELECT *
FROM teacher t LEFT JOIN student s ON s.teacher_id = t.id
(RIGHT JOIN would work if you want all student even if they do not have teachers)
Remmember that in SQL 1 == NULL and 1 != NULL are both false. So the following query will not result a teacher without students or a student without teachers.
SELECT *
FROM teacher t,
student s
WHERE s.teacher_id = t.id
I figured out my answer, in my select i was using dbo.Student.TeacherID, instead of dbo.Teacher.TeacherID, therefore my query was always coming back with null TeacherID values since I was checking my view with a query like this one
Select * from MyView Where TeacherID = 1;
This returned null since my select was pulling Student.TeacherID which is null, so I Swapped out dbo.Student.TeacherID for dbo.Teacher.TeacherID and it is now resolved.
Such a bleh moment. Thanks for comments and replies.!
As I am reading back in my OP, I said I was selecting
SELECT Teacher.TeacherID ,
Student.StudentID ,
which was technically a typo, but also my answer...