How to make Multi Table Sub Query less wordy Access - sql

I am trying to make a query to find all details of students interviewed more than once
I have gotten the results successfully using:
SELECT S.StudNo, S.StudLName, S.StudFName, S.StudMobile, S.City, S.DateEnrolled, S.ProgNo, S.AmountDue, S.Gender
FROM STUDENT AS S INNER JOIN STUDENT_INTERVIEW AS SI ON S.StudNo = SI.StudID
WHERE
(SELECT COUNT(SI.StudID)
FROM STUDENT_INTERVIEW)
GROUP BY S.StudNo, S.StudLName, S.StudFName, S.StudMobile, S.City, S.DateEnrolled, S.ProgNo, S.AmountDue, S.Gender
HAVING COUNT(SI.StudID) > 1;
But it seems excessively long.. I am trying to rewrite it to make it less wordy although am unable to get the correct results. I have been trying to use more sub queries to not have to use GROUP BY. When I do so I get the results for all students, not the specific 2 I'm after
SELECT *
FROM STUDENT
WHERE StudNo IN
(SELECT StudID
FROM STUDENT_INTERVIEW
WHERE
(SELECT COUNT(StudID)
FROM STUDENT_INTERVIEW
HAVING COUNT(StudID) > 1;))

Your first query is a good start. Here is an improvement:
SELECT S.*
FROM STUDENT AS S
WHERE S.StudNo IN (SELECT SI.StudId
FROM STUDENT_INTERVIEW as SI
GROUP BY SI.StudId
HAVING COUNT(*) > 1
);
The outer query needs neither the JOIN nor the GROUP BY. You can basically do all the work in the subquery.

Related

Getting distinct result without using the DISTINCT clause

I have the following code, I am able to get the result I desire by using DISTINCT but is there a way to get the same result without using DISTINCT?
SELECT S.name, COUNT(DISTINCT R.peopleID) AS numathletes
FROM Sports S
JOIN Results R ON S.ID = R.sportID
WHERE R.result >= S.record
GROUP BY S.name;
as for the tables i'm using:
Table S has ID, name, record
Table R has peopleID, competitionID, sportID, result
Yes, it is possible.
Here is one variant
SELECT name, COUNT(*) AS numathletes
FROM
(
SELECT S.name, R.peopleID
FROM
Sports S
JOIN Results R ON S.ID = R.sportID
WHERE R.result >= S.record
GROUP BY S.name, R.peopleID
) AS T
GROUP BY name;
It is a more verbose variant which shows clearly how the calculations are done.
You should try and check with your data and hardware which variant is faster.
Quite likely that they will perform the same.

SQL Not a GROUP BY expression

I'm still new to SQL.
I've got a query to count the number of students that attend a certain lecture and I've been trying to group the records by the lectureid so I don't have 10 records for the same lecture.
SELECT ATTENDANCESHEET.LECTUREID,TOPIC, (
SELECT COUNT(STUDENTID) AS ATTENDANCE
FROM ATTENDANCESHEET
WHERE ATTENDANCESHEET.STUDENTID = LECTURE.STUDENTID
)
FROM ATTENDANCESHEET,LECTURE
WHERE ATTENDANCESHEET.LECTUREID = LECTURE.LECTUREID
GROUP BY ATTENDANCESHEET.LECTUREID;
I'm getting the error "not a GROUP BY expression". Can someone help me, please?
The error is because you have a correlated query. The correlation clause (the where in the subquery) is using a column from the outer query that is not aggregated. In addition, you have a column topic that is not in the group by.
I believe the query you want is more simply written as:
select a.lectureid, count(*) as attendance
from attendancesheet a
group by a.lectureid;
I notice that you have topic in the select. That is also an issue. Perhaps you want:
select l.lectureid, l.topic, count(*) as attendance
from attendancesheet a join
lecture l
on a.lectureid = l.lectureid
group by l.lectureid;
Or, if you have studentid in lecture, perhaps:
select l.lectureid, l.topic, count(*) as attendance
from lecture l
group by l.lectureid;
EDIT:
The data structure doesn't make sense to me, but perhaps you need both keys for the join:
select l.lectureid, l.topic, count(*) as attendance
from attendancesheet a join
lecture l
on a.lectureid = l.lectureid and a.studentid = l.lectureid
group by l.lectureid;
to solve the issue of group by without knowing the expected result
SELECT ATTENDANCESHEET.LECTUREID,TOPIC, (
SELECT COUNT(STUDENTID) AS ATTENDANCE
FROM ATTENDANCESHEET
WHERE ATTENDANCESHEET.STUDENTID = LECTURE.STUDENTID
)
FROM ATTENDANCESHEET,LECTURE
WHERE ATTENDANCESHEET.LECTUREID = LECTURE.LECTUREID
GROUP BY ATTENDANCESHEET.LECTUREID,TOPIC,LECTURE.STUDENTID; -- added the topic and studentid from lecture table
but I think what he's trying to do is
SELECT ATTENDANCESHEET.LECTUREID,TOPIC, count(LECTURE.STUDENTID) cntstudent
FROM ATTENDANCESHEET,LECTURE
WHERE ATTENDANCESHEET.LECTUREID = LECTURE.LECTUREID
GROUP BY ATTENDANCESHEET.LECTUREID,TOPIC
Try adding TOPIC to the group by :)

Use result of multiple rows to do arithmetic operation

I'm writing a query to multiply the count that I receive from subquery to fees amount, But I don't know how to do that. Any help/suggestion?
Oracle query is:
select courseid,coursename,fees*tmp
from course c join registration r on
r.courseid=c.courseid
and tmp IN (select count(*)
from course c join registration r on
r.courseid=c.courseid group by coursename);
I tried to use like a variable tmp ,But i don't think it works in oracle query. Is there an alternative way to do so?
You can't do that, because you can only select data from tables that appeared between FROM and WHERE. The IN operator is a quick way to save having to write a bunch of OR statements, it is not something that can establish a variable in the outer query.
Instead do something like:
select courseid,coursename,fees * COUNT(r.courseID) OVER(PARTITION BY c.coursename)
from course c join registration r on
r.courseid=c.courseid
Edit/update: you noted that this query produces too many rows and you only want to see distinct course names. In that case it would be better to just use the registrations table to count the number of people on the course and then multiply the fees:
SELECT
c.courseid, c.coursename, c.fees * COALESCE(r.numberOfstudents, 0) as courseWorth
FROM
course c
LEFT OUTER JOIN
(select courseid, COUNT(*) as numberofstudents FROM registration GROUP BY courseid) r
ON c.courseID = r.courseid
You can use a windowing function like Caius or you can use a join like this:
select courseid,coursename, fees * COALESCE(sub.cnt,0)
from course c
join registration r on r.courseid=c.courseid
left join (
select coursename, count(*) as cnt
from course c2
join registration r2 on r2.courseid=c2.courseid
group by coursename
) as sub;
note: I make no claim your joins are correct -- I'm basing this query off of your example not on any knowledge of your data model.

Returning the Min() of a Count()

I am studying for an SQL test and the previous year has the final question:
Name the student who has studied the least number of papers. How many
papers have they studied?
So far, this is the select query that I have created:
select min(Full_Name), min(Amount)
from (select st.ST_F_Name & ' ' & st.ST_L_Name as Full_Name, count(*) as Amount
from (student_course as sc
inner join students as st
on st.ST_ID=sc.SC_ST_ID)
group by st.ST_F_Name & ' ' & st.ST_L_Name)
This works perfectly for returning the result I want but I'm not sure if this is the way I should be doing this query? I feel like calling min() on the Full_Name could potentially backfire on me under certain circumstances. Is there a better way to be doing this? (this is in MS Access for unknown reasons)
If you want only 1 of such students if there are multiple, this is probably the simplest:
select st.ST_F_Name, st.ST_L_Name, count(*) as Amount
from student_course as sc
inner join students as st
on st.ST_ID=sc.SC_ST_ID
group by st.ST_ID
order by Amount ASC LIMIT 1
However, if you want to find all stuch students, you follow a different approach. We use a WITH clause to simplify things, that defines a CTE (Common Table Expression) computing the number of courses per-student. And then we select students where their number equals to the minimum in that CTE:
with per_student as (
select st.ST_F_Name, st.ST_L_Name, count(*) as Amount
from student_course as sc
inner join students as st
on st.ST_ID=sc.SC_ST_ID
group by st.ST_ID
)
select * from per_student
where amount = (select min(amount) from per_student)
But the real trick in that question is that there might be students that didn't take ANY courses. But with approaches presented so far you'll never see them. You want something like this:
with per_student as (
select st.ST_F_Name, st.ST_L_Name, count(sc.SC_ST_ID) as Amount
from student_course as sc
right outer join students as st
on st.ST_ID=sc.SC_ST_ID
group by st.ST_ID
)
select * from per_student
where amount = (select min(amount) from per_student)
You can order by count(*) to get the student with the least # of papers:
i.e.
select * from students where st_id in (
select top 1 sc_st_id
from student_course
group by sc_st_id
order by count(*)
)
if you also need the # of papers studied, then join a derived table containing the min count:
select * from students s
left join (
select top 1 sc_st_id, count(*)
from student_course
group by sc_st_id
order by count(*)
) t on t.sc_st_id = s.st_id

How to join two SQL queries into one?

I'm new to SQL and I'm currently trying to learn how to make reports in Visual Studio. I need to make a table, graph and few other things. I decided to do matrix as the last part and now I'm stuck. I write my queries in SQL Server.
I have two tables: Staff (empID, StaffLevel, Surname) and WorkOfArt (artID, name, curator, helpingCurator). In the columns Curator and HelpingCurator I used numbers from empID.
I'd like my matrix to show every empID and the number of paintings where they're acting as a Curator and the number of paintings where they're acting as a Helping Curator (so I want three columns: empID, count(curator), count(helpingCurator).
Select Staff.empID, count(WorkOfArt.Curator) as CuratorTotal
FROM Staff, WorkOfArt
WHERE Staff.empID=WorkOfArt.Curator
and Staff.StaffLevel<7
group by Staff.empID;
Select Staff.empID, count(WorkOfArt.HelpingCurator) as HelpingCuratorTotal
FROM Staff, WorkOfArt
WHERE Staff.empID=WorkOfArt.HelpingCurator
and Staff.StaffLevel<7
group by Staff.empID;
I created those two queries and they work perfectly fine, but I need it in one query.
I tried:
Select Staff.empID, count(WorkOfArt.Curator) as CuratorTotal,
COUNT(WorkOfArt.HelpingCurator) as HelpingCuratorTotal
FROM Staff FULL OUTER JOIN WorkOfArt on Staff.empID=WorkOfArt.Curator
and Staff.empID=WorkOfArt.HelpingCurator
WHERE Staff.StaffLevel<7
group by Staff.empID;
(as well as using left or right outer join)
- this one gives me a table with empID, but in both count columns there are only 0s - and:
Select Staff.empID, count(WorkOfArt.Curator) as CuratorTotal,
COUNT(WorkOfArt.HelpingCurator) as HelpingCuratorTotal
FROM Staff, WorkOfArt
WHERE Staff.empID=WorkOfArt.Curator
and Staff.empID=WorkOfArt.HelpingCurator
and Staff.StaffLevel<7
group by Staff.empID;
And this one gives me just the names of the columns.
I have no idea what to do next. I tried to find the answer in google, but all explanations I found were far more advanced for me, so I couldn't understand them... Could you please help me? Hints are fine as well.
The easiest way to do this is most likely with inner select in the select clause, with something like this:
Select
S.empID,
(select count(*) from WorkOfArt C where C.Curator = S.empID)
as CuratorTotal,
(select count(*) from WorkOfArt H where H.HelpingCurator = S.empID)
as HelpingCuratorTotal
FROM Staff S
WHERE S.StaffLevel<7
group by S.empID;
This way the rows with different role aren't causing problems with the calculation. If the tables are really large or you have a lot of different roles, then most likely more complex query with grouping the items first in the WorkOfArt table might have better performance since this requires reading the rows twice.
From a performance perspective, the following query is probably a little more efficient
select e.EmpId, CuratorForCount, HelpingCuratorForCount
from Staff s
inner join ( select Curator, count(*) as CuratorForCount
from WorkOfArt
group by Curator) mainCurator on s.EmpId = mainCurator.Curator
inner join ( select HelpingCurator, count(*) as HelpingCuratorForCount
from WorkOfArt
group by HelpingCurator) secondaryCurator on s.EmpId = secondaryCurator.HelpingCurator
One method, that can be useful if you want to get more than one value aggregated value from the WorkOfArt table is to pre-aggregate the results:
Select s.empID, COALESCE(woac.cnt, 0) as CuratorTotal,
COALESCE(woahc.cnt) as HelpingCuratorTotal
FROM Staff s LEFT JOIN
(SELECT woa.Curator, COUNT(*) as cnt
FROM WorkOfArt woa
GROUP BY woa.Curator
) woac
ON s.empID = woac.Curator LEFT JOIN
(SELECT woa.HelpingCurator, COUNT(*) as cnt
FROM WorkOfArt woa
GROUP BY woa.HelpingCurator
) woahc
ON s.empID = woahc.HelpingCurator
WHERE s.StaffLevel < 7;
Notice that the aggregation on the outer level is not needed.