JOIN 3 tables and COUNT for result - sql

I am using an a join query between three tables. My query doesn't display entirely my desired result. There are three tables team, school and game. For example, how can I display the total wins Lawrence North High School(school_id = 11111) has?
Current query:
SELECT school.school_name
FROM school
INNER JOIN team ON school.school_id = team.school_id
INNER JOIN game ON team.team_id = game.game_id
WHERE school.school_id = 11111
tables used:
SQL> Select * From Team;
TEAM_ID SPORT_ID SCHOOL_ID TEAM_NAME
---------- ---------- ---------- ----------
1 1 11111 WildCats
2 2 11111 WILDCATS
3 3 11111 WildCats
4 4 11111 WILDCATS
5 5 11111 WildCats
6 6 11111 WildCats
7 7 11111 WildCats
8 1 123134 Bears
9 2 123134 Bears
10 3 123134 BEARS
11 4 123134 Bears
12 5 123134 Bears
13 6 123134 BEars
SQL> Select * From School;
SCHOOL_ID SCHOOL_NAME SCHOOL_TYPE
---------- ----------------------------- ------------
11546 Ivy Tech College COLLegE
11090 LAWRENCE Central Grade School GRADE SCHOOL
11111 Lawrence NORTH High School HIGH SCHooL
19283 Howe High SCHOOL High SchooL
123134 Lawrence Central High School HIGH SCHOOL
192 Little Big Horn Grade School GRADE SCHOOL
SQL> Select * From Game;
TEAM_ID GAME_DATE R
---------- --------- -
1 10-SEP-98 w
1 12-SEP-98 W
2 17-SEP-98 w
2 18-SEP-98 W
3 18-SEP-98 w
3 11-SEP-98 W
4 20-SEP-98 L
4 21-SEP-98 l
5 21-SEP-98 L
5 19-SEP-98 l
6 26-SEP-98 L
6 27-SEP-98 W
7 28-SEP-98 w
7 29-SEP-98 W
8 11-OCT-98 W
8 12-OCT-98 w
9 13-OCT-98 L
9 14-OCT-98 L
10 14-OCT-98 L
11 15-OCT-98 L
12 16-OCT-98 W
13 17-OCT-98 W
11 18-OCT-98 W
12 19-OCT-98 W
13 11-NOV-98
11 12-NOV-98

Try this
SELECT count(*) as Total_wins FROM school INNER JOIN team ON school.school_id = team.school_id INNER JOIN game ON team.team_id = game.game_id WHERE school.school_id = 11111 and game.r = 'W'

You can use the COUNT With Where clause with Group By on the schoolname.
SELECT school.school_name, COUNT(game.R) as TotalWins
FROM school INNER JOIN team
ON school.school_id = team.school_id
INNER JOIN game
ON team.team_id = game.game_id
WHERE
school.school_id = 11111
AND game.R = 'W'
If you are doing it for the one school you can just remove the Group By but if you want to get the count for all schools you need to apply the Group By and remove the Chool_id filter from Where clause.

You will also have to specify the sport id in the where clause.
where school.school_id = 11111 and
team.sportid = (what ever the sport id you want to see)

Related

Select max date for each register, null if does not exists

I have these tables: Employee (id, name, number), Configuration (id, years, licence_days), Periods (id, start_date, end_date, configuration_id, employee_id, period_type):
Employee table:
id name number
---- ----- -------
1 Bob 355
2 John 467
3 Maria 568
4 Josh 871
configuration table:
id years licence_days
---- ----- ------------
1 1 8
2 3 16
3 5 24
Periods table:
id start_date end_date configuration_id employee_id period_type
---- ---------- ------- ---------------- ----------- -----------
1 2021-05-23 2021-05-31 1 1 vaccation
2 2021-05-24 2021-06-01 1 2 vaccation
3 2021-03-01 2021-03-17 2 2 vaccation
4 2021-05-05 2021-05-21 2 2 vaccation
5 2021-01-01 2021-01-17 2 4 vaccation
I want this result:
Result:
employee_id years licence_days max(end_date)
1 1 8 2021-05-31
1 3 16 null
1 5 24 null
2 1 8 2021-06-01
2 3 16 2021-05-21
2 5 24 null
3 1 8 null
3 3 16 null
3 5 24 null
4 1 8 null
4 3 16 2021-01-17
4 5 24 null
i.e., I want to select all Employees with all configuration, and for each one of that, the max end_date of the "vaccation" type (or null if it does not exists).
How can I do that
Oracle supports cross joins, right? So may be something like that?
SELECT e.employee_id, c.years, c.licence_days, max(p.end_date)
FROM Employee e
CROSS JOIN configuration c
LEFT JOIN Periods p
ON e.employee_id = p.employee_id
AND c.configuration_id = p.configuration_id
GROUP BY e.employee_id, c.years, c.licence_days
ORDER BY e.employee_id, c.years
#umberto-petrov chooses wisely with the ANSI CROSS JOIN syntax for a cartesian join. However, in the very weak probability that your requires output of configurations even where there is no employees, you can go with something like :
EDIT: Filtering the Periods join with 'vaccation' as asked in the comments.
If you have to filter for some employee ids, change ON 1 = 1 by ON Employee.id IN (id1, id2, ...). It still keeps every configurations but only takes employees that match the ids.
SELECT Employee.employee_id,
Configuration.years,
Configuration.licence_days,
MAX(Configuration.end_date) max_end_date
FROM Configuration LEFT JOIN Employee ON 1 = 1
LEFT JOIN Periods ON Periods.configuration_id = Configuration.id
AND Periods.employee_id = Employee.id
AND Periods.period_type = 'vaccation'
GROUP BY Employee.employee_id,
Configuration.years,
Configuration.licence_days
ORDER BY Employee.employee_id,
Configuration.years,
Configuration.licence_days
We start from configuration to take every records from this one at least, then made a LEFT CARTESIAN JOIN with Employee and finally a full LET JOIN on Periods for both. That way , if there is no employees, this will output configuration_id and NULL for years, licence_days and max end_date.

ORACLE DB query - maximum stipend in faculty

So, i have an task in uni to get max stipend in each faculty from a table with stipends.
Faculty table is:
ID_FACULTY FACULTY_NAME DEAN TELEPHON
---------- ------------------------------ -------------------- --------
10 Informacijas tehnologiju Vitols 63023095
11 Lauksaimniecibas Gaile 63022584
12 Tehniska Dukulis 53020762
13 Partikas tehnologijas Sabovics 63021075
Money table is:
ID_PAYOUT STUDENT_ID PAYOUT_DA STIPEND COMPENSATION
---------- ---------- --------- ---------- ------------
100 1 24-SEP-20 45.25 15
101 7 20-SEP-20 149.99 0
102 3 18-SEP-20 100 0
103 17 02-SEP-20 90.85 20
104 9 03-SEP-20 85 20
105 19 09-SEP-20 70.75 0
106 25 15-SEP-20 55 15
107 17 17-SEP-20 105.54 0
108 15 22-SEP-20 94 0
109 27 28-SEP-20 100 20
And the student table is:
ID_STUDENT SURNAME NAME COURSE_YEAR FACULTY_ID BIRTHDATE
---------- ------------------------- -------------------- ----------- ---------- ---------
1 Lapa Juris 4 13 27-SEP-96
3 Vilkauss Fredis 2 10 17-MAY-99
5 Karlsone Rasa 1 11 13-MAR-00
7 Grozitis Guntars 3 12 16-APR-97
9 Sonciks Jurgis 2 10 17-MAR-99
11 Berzajs Olafs 3 10 14-FEB-97
13 Vike Ilvija 2 13 14-MAY-99
15 Baure Inga 3 11 12-APR-97
17 Viskers Zigmunds 2 13 15-AUG-99
19 Talmanis Harijs 3 13 15-JUL-97
21 Livmanis Indulis 1 10 19-JAN-00
23 Shaveja Uva 2 13 18-FEB-98
25 Lacis Guntis 4 10 17-SEP-96
27 Liepa Guna 4 11 18-AUG-96
29 Klava Juris 2 10 19-MAY-98
I have tried many variations of queries, i think that I even tried all the possible combinations of joins, but i cannot achieve the neccessary result.
One of my queries looked like this:
SQL> SELECT ROW_NUMBER() OVER (ORDER BY surname) "Nr.",
f.faculty_name,
s.surname,
s.name,
MAX(m.stipend)
FROM faculty f, student s INNER JOIN money m ON s.id_student = m.student_id
WHERE s.faculty_id = f.id_faculty
GROUP BY f.faculty_name, s.surname, s.name
ORDER BY s.surname;
Which returned me the following result:
Nr. FACULTY_NAME SURNAME NAME MAX(M.STIPEND)
---------- ------------------------------ ------------------------- -------------------- --------------
1 Lauksaimniecibas Baure Inga 94
2 Tehniska Grozitis Guntars 149.99
3 Informacijas tehnologiju Lacis Guntis 55
4 Partikas tehnologijas Lapa Juris 45.25
5 Lauksaimniecibas Liepa Guna 100
6 Informacijas tehnologiju Sonciks Jurgis 85
7 Partikas tehnologijas Talmanis Harijs 70.75
8 Informacijas tehnologiju Vilkauss Fredis 100
9 Partikas tehnologijas Viskers Zigmunds 105.54
9 rows selected.
So the goal of this task is to retrieve the maximum amount of stipend granted to a student in a certain faculty.
Can someone please tell what am I doing wrong here?
Just max amount per faculty:
SELECT
f.faculty_name,
MAX(m.stipend)
FROM
faculty f
INNER JOIN student s ON s.faculty_id = f.id_faculty
INNER JOIN money m ON s.id_student = m.student_id
GROUP BY f.faculty_name
Max amount and all other details too:
SELECT * FROM
(
SELECT
ROW_NUMBER() OVER (PARTITION BY f.faculty_name ORDER BY m.stipend desc) rn,
f.*,
s.*,
m.*
FROM
faculty f
INNER JOIN student s ON s.faculty_id = f.id_faculty
INNER JOIN money m ON s.id_student = m.student_id
) x
WHERE x.rn = 1
Points of note:
Do not use old style joins; if you ever write one table_name, other_table_name in a FROM block, you're using old style joins. Don't do it; they became bad news about 30 years ago
When you have a max-n-per-group, you specify how finely detailed the group is. If you GROUP BY s.first_name, s.last_name, f.faculty_name then your groups are "every unique combination of firstname/lastname/faculty, so the only way you'll get multiple items in your group is if there are two John Smiths in Mathematics. If the group is to be the whole of mathematics, then the faculty name (and anything else that is uniquely related 1:1 to it, like the faculty ID) is all that you can put in your group. Anything not in a group must be in an aggregation, like MAX
When you want other details too, you either group and max the data and then join this groupmaxed data back to the original data to use it as a filter, or you use an approach like here where you use a row_number or rank, with a partition (which is like an autojoined grouped summary). There is no group here; the row numbering acts like a group because it restarts from 1 every different faculty and proceeds incrementally as stipend decreses. This means that the highest stipend is always in row number 1.
Unlike using a groupmax that you join back to get the detail, the row_number route does not produce duplicate rows with tied-for-highest stipends

How do I display rows from a max count?

I want to return all the data, from max count query with hospital that has most number of patients. What I seem to be getting when I try to nest queries is display of all rows of hospital data. I've tried to look at similar questions in stack overflow and other sites it seems to be a simple query to do but i am not getting it.
select max(highest_hospital) as max_hospital
from (select count(hospital) as highest_hospital
from doctor
group by hospital)
highest_hospital
-------------
3
Doc ID Doctor Patient Hospital Medicine Cost
------ ------- ------ --------- ------ --------
1 Jim Bob Patient1 Town 1 Medicine 1 4000
2 Janice Smith Patient2 Town 2 Medicine 3 3000
3 Harold Brown Patient3 Town 2 Medicine 5 2000
4 Larry Owens Patient4 Town 2 Medicine 6 3000
5 Sally Brown Patient5 Town 3 Medicine 7 4000
6 Bob Jim Patient6 Town 4 Medicine 8 6000
Outcome should be return of 3 rows
Doc ID Doctor Patient Hospital Medicine Cost
------ ------- ------ --------- ------ --------
2 Janice Smith Patient2 Town 2 Medicine 3 3000
3 Harold Brown Patient3 Town 2 Medicine 5 2000
4 Larry Owens Patient4 Town 2 Medicine 6 3000
You can use window functions:
select d.*
from (select d.*, max(hospital_count) over () as max_hospital_count
from (select d.*, count(*) over (partition by hospital) as hospital_count
from doctor d
) d
) d
where hospital_count = max_hospital_count;
Edit:
Using GROUP BY is a pain. If you are only looking for a single hospital (even when there are ties), then in Oracle 12C you can do:
select d.*
from doctor d
where d.hospital = (select d2.hospital
from doctor d2
group by d2.hospital
order by count(*) desc
fetch first 1 row only
);
You can do this in earlier versions of Oracle using an additional subquery.

SQL SELECT query to pull data from tables to calculate a sum

I have four tables in a database, what I want to do is essentially list the employee number, name department number of any projects they are working on and the total hours that they spend working on projects.
I'm trying to do this all as one single SELECT statement, but am having trouble getting it to work with Oracle SQL. My latest attempt has been
SELECT EMPLOYEE.E#, EMPLOYEE.NAME, SUM(WORKSON.HOURS)
FROM EMPLOYEE JOIN WORKSON ON EMPLOYEE.E#=WORKSON.E#
GROUP BY EMPLOYEE.E#;
Which isn't even the complete statement, and gives me the error:
ERROR at line 1:
ORA-00979: not a GROUP BY expression
What can I do to complete the statement to also include the department number and what should I be doing? Should I be using a join for this? or should I be incorporating another SELECT statement within a WHERE clause?
The tables are as follows:
EMPLOYEE:
SQL> SELECT * FROM EMPLOYEE;
E# NAME DOB S SALARY SUPER D#
----- ------------------ ----------- -- ------ -------- ---
00100 Albert 13-OCT-65 M 186.5
00110 Alvin 13-OCT-77 M 156.4 00100 1
00120 Alice 17-JUN-73 F 156.5 00100 2
00150 Bob 02-JUL-60 M 166.4 00100 3
00200 Carl 02-FEB-67 M 156.3 00100 4
00250 Douglass 14-APR-83 M 156.4 00100 5
00101 Peter 13-NOV-76 M 85.2 00110 1
00103 Ami 12-SEP-85 F 78.2 00110 1
00107 Wendy 12-SEP-88 F 68.2 00110 1
00109 Michael 12-SEP-90 M 58.2 00110 1
00125 Angela 20-NOV-90 F 56.4 00120 2
00105 Robert 15-JAN-86 M 66.2 00150 3
00136 Aban 15-JAN-90 M 55.3 00200 4
00187 Eadger 07-APR-86 M 76.5 00250 5
14 rows selected.
WORKSON:
SQL> SELECT * FROM WORKSON;
E# P# HOURS
----- ------- -----
00110 1001 10
00101 1001 20
00150 1002 10
00105 1002 10
00105 1003 20
00105 1004 20
00250 1004 15
00187 1004 25
00105 1005 15
DEPARTMENT:
SQL> SELECT * FROM DEPARTMENT;
D# DNAME MANAG MSDATE
-- ------------------ ------ ------------
1 SALES 00110 02-JAN-12
2 ACCOUNTING 00120 30-OCT-10
3 GAMES 00150 01-MAR-08
4 HUMAN RESOURCES 00200 02-JAN-13
5 SPORTS 00250 10-MAY-10
PROJECT:
SQL> SELECT * FROM PROJECT;
P# PTITLE SPONSOR D# BUDGET
------ --- -------------- ---------------------- --- -------
1001 Computation Microsoft 1 25000
1002 Study methods Education committee 3 15000
1003 Racing car Cloud Pty Ltd 3 225000
1004 Football Football club 5 35000
1005 Swimming Education committee 5 125000
Any help would be greatly appreciated. Thanks in advance!
You first find the sum of hours of each employee and then join the same with your main table. Inline view can be used for the same.
SELECT EMPLOYEE.E#, EMPLOYEE.NAME, NVL(WORKSON_AGGR.TOTAL_HOURS,0)
FROM EMPLOYEE
LEFT JOIN (SELECT E#, SUM(HOURS) as TOTAL_HOURS
FROM WORKSON
GROUP BY E# ) WORKSON_AGGR
ON (WORKSON_AGGR.E# = EMPLOYEE.E#)
Now, you can join your department table too easily.
SELECT
E.E#,
E.NAME,
NVL(WORKSON_AGGR.TOTAL_HOURS,0),
D.DNAME
FROM EMPLOYEE E
LEFT JOIN (SELECT E#, SUM(HOURS) as TOTAL_HOURS
FROM WORKSON
GROUP BY E# ) WORKSON_AGGR
ON (WORKSON_AGGR.E# = E.E#)
JOIN DEPARTMENT D ON (D.D# = E.D#)

How does select query works?

I having trouble with this query
it is executing quit well but I cannot make out
how is this select statement working.
Any help or explanation on this problem will be appreciated ..
thank you
these are my tables and query
here am looking for the employee who lives in same city as the the company for which they work
Table:-emp
eid name street city
----------- ---------------- ------------- ------------
1 yeman asd vasai
2 aksh adssd mumbai
3 chintan ghfgh mumbai
4 samual ghfdgh bandra
5 ddlj fghfgh andheri
6 jack fghnfg Bandra
7 bridge gfhfgh vasai
8 rahim ghfgh mumbai
9 chirag fghfghfg bandra
10 mistry hhhty bandra
11 ravi tytey andheri
Table:- company
cid companyname city
----------- ------------------- ------------
1 Vasai Industries vasai
2 Mumbai Pharmacy mumbai
3 bandra loft bandra
4 andheri tactics andheri
Table:= works
eid cid salary
----------- ----------- -----------
1 1 200
2 3 4831
3 4 4457
4 2 20001
5 1 32221
6 2 224
7 3 784
8 1 336
9 3 2489
10 2 4789
11 1 22541
Query
select * from emp
where eid
IN (select eid from works
where cid=(select cid from company
where city=emp.city))
why not use this query with joins and its easy to understand then a bunch of subqueries.
select * from emp
inner join works on works.eid = emp.eid
inner join company on company.city=emp.city
Explanation:
1.select cid from company where city=emp.city
Here you are getting city id regarding cities which are same in emp and company
2.
select eid from works
where cid=(select cid from company
where city=emp.city)
Here you getting collection of id's from works table which cid is same in emp and company
3.
select * from emp
where eid
IN (select eid from works
where cid=(select cid from company
where city=emp.city))
here you are getting all records based on emp id's whose cities are same in emp and city