I want to make a query that gives me the max and min average mark of students. I can get the max and min marks, but I don't know how to caluclate average of those.
SELECT MAX(mark) AS Max_mark FROM passed
GROUP BY student_id;
This gives the max mark from every student, I need average of that values.
Use AVG to get the avarage per student. Use MIN and MAX on this to get the highest and lowest avararage over all students.
select
min(avg_mark) as min_avg_mark,
max(avg_mark) as max_avg_mark
from
(
select avg(mark) as avg_mark
from passed
group by student_id
) as avg_marks;
SELECT student_id, (MAX(mark) + MIN(mark)) / 2 AS Avg_mark FROM passed
GROUP BY student_id;
Or are you looking for average
SELECT student_id, AVG(mark) as Avg_mark FROM passed
GROUP BY student_id;
Related
I'm taking a SQL class and I need help with a question.
I have the following table on a phpmyadmin server
patient (id, age)
with a total of 100 patients
I'm told to find the sum of people that have same age using SQL.
I wrote this query:
SELECT COUNT(age)
FROM patient
HAVING (COUNT(age) > 1);
but it returns 100 as a result and when I did this query and found the number of patients who have the same age for each age and calculated the count manually I found 78 and I checked it manually and it's indeed 78.
SELECT COUNT(*)
FROM patient
GROUP BY age
HAVING (COUNT(*) > 1);
What's wrong with my code?
Start with a subquery that gets the counts of people with each age. Then filter this to counts more than 1 so it's just people with the same age.
Then in the main query you use SUM() to add all these counts together, to get the total number of patients.
SELECT SUM(count)
FROM (
SELECT COUNT(*) AS count
FROM patient
GROUP BY age
HAVING count > 1
) AS x
select age, count(*) from patient group by age;
Write a query to find the highest average sales among all the salespersons using the given table.
Table: Sales
Field Type
InvoiceNo Integer
SalesPerson Text
TotalSale Integer
Sample
InvoiceNo SalesPerson TotalSale
1 Acheson 50
2 Bryant 25
3 Bennett 250
4 Acheson 50
5 Bryant 100
6 Bennett 250
Sample output
max(totalsale)
250.0000
I tried using: SELECT MAX(TotalSale) FROM Sales. My output for sample test case was 250 but it was given wrong answer verdict in an online judge.
Also, when I changed the query to : SELECT MAX(TotalSale*1.0000) FROM Sales,I got correct answer for sample test case but still wrong answer for other test cases.
What is meant by average here? What should be the query?
Also, this isn't from any on-going competition. It is from a practice test which you can attempt here: https://www.hackerearth.com/challenge/test/kredx-data-analyst-test/
1.First you have to calculate the average TotalSale for each SalesPerson using the AVG function.
SELECT SalesPerson, AVG(TotalSale) AS 'TotalSale'
FROM Sales
GROUP BY SalesPerson
2.Find out the max value from the table generated by the above query.
SELECT MAX(avgSales.TotalSale)
FROM (SELECT AVG(TotalSale) AS 'TotalSale' FROM Sales GROUP BY SalesPerson) AS avgSales
SELECT avg(TotalSale) as MaxTotal
FROM Sales
GROUP BY Salesperson
ORDER BY MaxTotal desc
LIMIT 1
Output:
MaxtTotal
250.0000
The average sale would use the avg() function:
select salesperson, avg(totalsale) as avg_totalsale
from sales
group by salesperson;
The maximum of the average can be obtained using order by and limit:
select avg(totalsale) as avg_totalsale
from sales
group by salesperson
order by avg_totalsale desc
limit 1;
Here is another way to answer this:
select avg(TotalSale)
from Sales
group by SalesPerson
order by totalSale desc limit 1;
output:
avg(TotalSale)
250.0000
Minor change to #gordon-linoff 's answer to pass the sample test case.
select CAST(avg(totalsale) AS DECIMAL(16,4)) as avg_totalsale
from sales
group by salesperson
order by avg_totalsale desc
limit 1;
CAST(avg(totalsale) AS DECIMAL(16,4))
The above part will restrict the zero's in decimal place up to 4. Convert 250.00000000 to 250.0000
SELECT max(avgsale.TotalSale)
FROM (Select Cast(Round(Avg(TotalSale),2) as dec(10,4)) 'TotalSale' from Sales
GROUP BY salesPerson) avgsale
How to get the maximum from averages values in MySQL? The following query returns average values of amounts from table orders grouped by customers.
SELECT AVG(amount)
FROM orders
GROUP BY cust;
I want to receive a maximum value from average values using a single query with aggregate functions. Using ORDER BY ... DESC LIMIT 1 surely works, but what I am interested in is getting the maximum average value using aggregate functions solely. Is it possible at all? Thanks
select max(avg_value)
from
(
SELECT AVG(amount) avg_value FROM orders GROUP BY cust
) tmp
I would do this with order by and limit:
SELECT AVG(o.amount) as avg_value
FROM orders o
GROUP BY cust
ORDER BY avg_value DESC
LIMIT 1;
This allows you to get the cust for the maximum as well.
I'm storing ratings for an item in a table called ratings.
value is an integer between 0 and 7 (the rating value).
As an example, let's say showcase_id = 1 has 10 total ratings:
5 ratings are value = 7
2 ratings are value = 6
2 ratings are value = 5
1 rating is value = 4
no ratings for values 0,1,2,3
Is there any efficient way I can select the total number of ratings for each specific value, the total number of ratings and the average rating from 1 single query?
e.g. the number of rows/count WHERE value = 6 is 2. Would I need to do 7 separate subqueries?
SELECT AVG(value),COUNT(*),????
FROM ratings
WHERE showcase_id = :showcase_id
Are you referring to count(distinct)?
SELECT AVG(value), COUNT(*), COUNT(DISTINCT value)
FROM ratings
WHERE showcase_id = :showcase_id;
EDIT:
If you want the total for each value, you can stuff this into one column, using a subquery:
SELECT SUM(cnt * value) / SUM(cnt) as average,
SUM(cnt) as total_cnt,
GROUP_CONCAT(value, '-', cnt ORDER BY VALUE) as values
FROM (SELECT value, COUNT(*) as cnt
FROM ratings r
WHERE showcase_id = :showcase_id
GROUP BY value
) r;
Perhaps the subquery meets your needs as well.
You can use the WITH ROLLUP modifier to GROUP BY to get the counts and average for each value, as well as the totals for everything (if you group by multiple columns it will also create subtotals for each inner group).
SELECT value, AVG(value) AS avg, COUNT(*) as count
FROM ratings
WHERE showcase_id = 1
GROUP BY value WITH ROLLUP
This will produce a row for each value with its count, and then a row with value = NULL for that aggregates the entire result.
DEMO
What's wrong with group by?
SELECT AVG(value),COUNT(*), value
FROM ratings
WHERE showcase_id = :showcase_id
GROUP BY value;
EDIT (with the overall avg & totes):
select count(*) total_by_value, value, s1.full_avg, s1.full_total
from ratings r,
(select avg(value) full_avg, count(*) full_total from ratings) s1
group by s1.full_avg, s1.full_total, value;
I am building a query in mysql 5.0 to calculate a student semester grade. The initial table (studentItemGrades) contains the list of assignments etc which will be used to calculate the final grade. Each assignment has a PossibleScore, Grade and Weight. The calculation should group all similarly weighted items, and provide the SUM(GRADE)/SUM(POSSIBLESCORE) based on a date range of when the assignment was due. The problem I am encountering is the final summation of all the individual weighted grades. For example, the results currently produce the following:
CourseScheduleID sDBID AssignedDate DueDate Weight WeightedGrade
1 519 2010-08-26 2010-08-30 10 0.0783333333333333
1 519 2010-09-01 2010-09-03 20 0.176
1 519 2010-09-01 2010-09-10 70 0.574
from the query:
SELECT CourseScheduleID, sDBID, AssignedDate, DueDate, Weight,
((SUM(Grade)/SUM(PossibleScore))*(Weight/100)) AS WeightedGrade
FROM studentItemGrades
WHERE DueDate>='2010-08-23'
AND DueDate<='2010-09-10'
AND CourseScheduleID=1
AND sDBID=519
AND Status>0
GROUP BY Weight
The question: How do I now SUM the three results in the WeighedGrade output? And by the way, this is part of a much larger query for calculating all grades for all courses on a particular campus.
Thanks in advance for your help.
You can use a subquery, like so:
SELECT SUM(WeightedGrade) FROM
(
SELECT CourseScheduleID, sDBID, AssignedDate, DueDate, Weight,
((SUM(Grade)/SUM(PossibleScore))*(Weight/100)) AS WeightedGrade
FROM studentItemGrades
WHERE DueDate>='2010-08-23'
AND DueDate<='2010-09-10'
AND CourseScheduleID=1
AND sDBID=519
AND Status>0
GROUP BY Weight
) t1
In order to sum the three results, you would need to requery the results of this select using another select with a group by. This could be done using a single sql statement by using subqueries.
SELECT sq.CourseScheduleID, sq.sDBID, SUM(sq.WeightedGrade) as FinalGrade
FROM
(
SELECT CourseScheduleID, sDBID, AssignedDate, DueDate, Weight,
((SUM(Grade)/SUM (PossibleScore))*(Weight/100)) AS WeightedGrade
FROM studentItemGrades WHERE DueDate>='2010-08-23' AND DueDate<='2010-09-10'
AND CourseScheduleID=1 AND sDBID=519 AND Status>0 GROUP BY Weight
) AS sq
GROUP BY sq.CourseScheduleID, sq.sDBID