Assign rank automatically with its total score - mysql

I have managed my db in MySQL. My table looks like this:
.
There are a total of 6 types of ratings for each hospital. Each rating has max score of 10. Users vote each rating total of 10. I want to know how do I structure my query that it should automatically calculates rank of each hospital according to its total of rating values. Suppose hospital A has total (180) & hospital B has total (120) then hospital A given auto ranking as 1 & hospital B as 2. Since I have limited knowledge on sql I am not able to structure proper query.
Types of ratings are (charges, behaviour, admission, properInformation, hygine, treatment)

You will want to use a combination of GROUP BY and SUM.
Here are two good resources to help you with your problem.
MYSQL SUM GROUP BY
https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

Related

Total amount of sales done for each product using SQL

Here is the structure of 1st Table called Product.
PRODID PDESC PRICE CATEGORY DISCOUNT
101 BALL 10 SPORTS 5
102 SHIRT 20 APPAREL 10
Here is the structure of 2nd table called SaleDetail.
SALEID PRODID QUANTITY
1001 101 5
1001 101 2
1002 102 10
1002 102 5
I am trying to get total sales amount for each product by joining 2 tables. Here is the SQL i tried but its not giving correct result.
select a.prodid,
(sum((price - discount))),
sum(quantity),
(sum((price - discount))) * sum(quantity)
from product a
join saledetail b on a.prodid = b.prodid
group by a.prodid
2nd column of the query is giving incorrect final price. Please help me correct this SQL.
Please find an indicative answer to your question in the fiddle.
A problem stems from the aggregation of the difference of price. In case that the same product has two different prices, then these prices would be aggregated to one.
Moreover, you multiple the sums of the prices and quantities, while you need to perform the calculation on every sample. Look at the answer by #DanteTheSmith.
You might consider to use the SaleDetail table on the left side of your query.
SELECT SD.PRODID,
P.Price-P.Discount AS Final_Price,
SUM(SD.QUANTITY) AS Amount_Sold,
SUM((P.Price-P.Discount)*SD.QUANTITY) AS Sales_Amount
FROM SaleDetail AS SD
JOIN Product AS P
ON SD.PRODID = P.PRODID
GROUP BY SD.PRODID, P.Price-P.Discount
It would help if you built the example in SQL fiddle or gave the creates for the tables, but if I have to guess your problem is:
(sum((price - discount))) * sum(quantity)
needs to be:
sum((price - discount) * quantity)
(price - discount) * quantity is the function you wanna apply PER ROW of the joined table then you wanna add all those up with SUM() when grouping by prodid.
Furthermore, you can notice that (price - discount) needs to be done ONLY ONCE PER ROW so a quicker version would be to do:
(price-discount) * sum(quantity)
That would give you the total money earned for that product across all the sales you made, and I am guessing this is what you want?
I just notice you have a problem with 2nd column, dunno if that has been in question all along:
(sum((price - discount)))
Why are you summing? Do you want the money earned per product per unit of the product? Well guess what, your price is the same all the time, same as your discount so you can simply go with:
(price-discount) as PPP
NOTE: This assumes the discount is numerical (not percentage) and is applicable to all your sales, also the price is forever the same all which is not real life like.

Show IDs for the highest MAX values in a matrix

I have a matrix that's grouped by different company brands. Essentially, I'm showing the highest value spent by a customer for each company brand (I've used MAX in my expression to get those). I also want to show Customer IDs attributed to those MAX values. Does anybody know how to do that? Is there any expression?
Example:
Company Brand: Nike | Max value spent: £500 | Customer ID: ???
Thanks
You can use subqueries to retrieve summed values in your SQL Query
SELECT T1.CustomerID, T1.CompanyBrand,
(SELECT Max(S1.ValueSpentField) FROM TableThatContainsValueSpent S1 WHERE T1.CustomerID = S1.CustomerID)
FROM Company T1

SELECT rows having equal column(c1) value and adding adding another column(c2) value. Performing same for all the distinct column values for column c1

I need to write an SQL Query for MySQL Database which gives me the data according to the necessary conditions
I have a table having structure like this
id: orderId
amount : itemAmount
rate : itemRate
time : orderTime
Now I have to select all the rows having same rates and then have to add all the items having same rates. This should work for each rate means for eg.
row with id 1 is having rate $20 with 2 items and row 3 is having rate $20 with 5 items
row with id 2 is having rate $40 with 4 items and row 4 is having rate $40 with 7 items
I should get result is
rate: $20 totalItem : 7
rate: $40 totalItem : 11
As I stated in my comment, I don't know what your columns are called, I'll assume in my answer they're called id, amount, rate and time.
SELECT rate, COUNT(*) AS totalItems -- Select the rate, and count everything
FROM theRelevantTable -- Use the rows in this table
GROUP BY rate -- But do the selection per group.
In clearer English:
Group the rows in theRelevantTable by their rate, then, for every group, give me the rate and count how many rows there are in the group.
I hope this is what you meant. I do not entirely understand your question.
maybe this? SQL FIDDLE to play with
ASSUMPTIONS: you have a table called orders with columns rate, amount, time, id.
amount stores a quantity of items, rate is the price they are at, and time is when it occurred.
SELECT
rate,
SUM(amount)
FROM orders
GROUP BY rate

Relational Database Logic

I'm fairly new to php / mysql programming and I'm having a hard time figuring out the logic for a relational database that I'm trying to build. Here's the problem:
I have different leaders who will be in charge of a store anytime between 9am and 9pm.
A customer who has visited the store can rate their experience on a scale of 1 to 5.
I'm building a site that will allow me to store the shifts that a leader worked as seen below.
When I hit submit, the site would take the data leaderName:"George", shiftTimeArray: 11am, 1pm, 6pm (from the example in the picture) and the shiftDate and send them to an SQL database.
Later, I want to be able to get the average score for a person by sending a query to mysql, retrieving all of the scores that that leader received and averaging them together. I know the code to build the forms and to perform the search. However, I'm having a hard time coming up with the logic for the tables that will relate the data. Currently, I have a mysql table called responses that contains the following fields,
leader_id
shift_date // contains the date that the leader worked
shift_time // contains the time that the leader worked
visit_date // contains the date that the survey/score was given
visit_time // contains the time that the survey/score was given
score // contains the actual score of the survey (1-5)
I enter the shifts that the leader works at the beginning of the week and then enter the survey scores in as they come in during the week.
So Here's the Question: What mysql tables and fields should I create to relate this data so that I can query a leader's name and get the average score from all of their surveys?
You want tables like:
Leader (leader_id, name, etc)
Shift (leader_id, shift_date, shift_time)
SurveyResult (visit_date, visit_time, score)
Note: omitted the surrogate primary keys for Shift and SurveyResult that I would probably include.
To query you join shifts and surveys group on leader and taking the average then jon that back to leader for a name.
The query might be something like (but I haven;t actually built it in MySQL to verify syntax)
SELECT name
,AverageScore
FROM Leader a
INNER JOIN (
SELECT leader_id
, AVG(score) AverageScore
FROM Shift
INNER JOIN
SurveyResult ON shift_date = visit_date
AND shift_time = visit_time --depends on how you are recording time what this really needs to be
GROUP BY leader ID
) b ON a.leader_id = b.leader_id
I would do the following structure:
leaders
id
name
leaders_timetabke (can be multiple per leader)
id,
leader_id
shift_datetime (I assume it stores date and hour here, minutes and seconds are always 0
survey_scores
id,
visit_datetime
score
SELECT l.id, l.name, AVG(s.score) FROM leaders l
INNER JOIN leaders_timetable lt ON lt.leader_id = l.id
INNER JOIN survey_scores s ON lt.shift_datetime=DATE_FORMAT('Y-m-d H:00:00', s.visit_datetime)
GROUP BY l.id
DATE_FORMAT here helps to cut hours and minutes from visit_datetime so that it could be matched against shift_datetime. This is MYSQL function, so if you use something else you'll need to use different function
Say you have a 'leader' who has 5 survey rows with scores 1, 2, 3, 4 and 5.
if you select all surveys from this leader, sum the survey scores and divide them by 5 (the total amount of surveys that this leader has). You will have the average, in this case 3.
(1 + 2 + 3 + 4 + 5) / 5 = 3
You wouldn't need to create any more tables or fields, you have what you need.

How to perform this MySQL query given this relation diagram

I have the following relation diagram where arrows represent Foreign Keys. The word in the blue is the table name and the words below are column names.
My question is how I could extract the following data from this table:
-what is the GPA of the student with ID=1?
-what are the average GPAs for students by department?
Given that: there are only
five letter grades with values A=4, B=3, C=2, D=1, and F=0, and GPA is the sum of
course credits x course grade value divided by total credits x 4. (so takes.grade is an int from 0-4 inclusive).
I have been trying to figure this out for hours with no avail. Could anyone steer me in the right direction?
Thanks for any help.
Ok, I've actually had to do this for a client over 15 yrs ago, and did for the entire database of all students, not as difficult once you have the pieces.
Without your exact queries as you want guidance.
Start with a single query that pulls data into a TEMPORARY table
CREATE TEMPORARY TABLE AllStudentsCourses
SELECT blah... from blah... join blah.. where... order by ...
A list of all classes a person has signed up for, and while you are at it, have columns computed at the PER-CLASS BASIS the grade earned A-F. You'll also need the credit hours of the class too as that is basis of computing a GPA.
a 3 hour course with an A gets 3 cr hrs towards GPA.
a 6 hour course with an A gets 6 cr hrs towards GPA.
a 6 hour course with a B gets LESS weighted value towards GPA
and you'll need to roll aggregates up.
Now, once you have all the classes a student attempted, you'll need to compute the per-class as sample described. If you want to apply that in the first query, do so.
Once you have that, then, you can roll-up the total credit hrs attempted vs credit hrs earned.
Basic math should help you along.
I didn't quite understand how the GPA is calculated, think there is something wrong with your original post. Here's a starting point that may or may not be right:
SELECT avg(t.grade)
FROM takes t
INNER JOIN course c
ON t.course_id = c.course_id
WHERE t.ID = 1;
SELECT c.dept_name, avg(grade)
FROM takes t
INNER JOIN course c
ON t.course_id = c.course_id
GROUP BY c.dept_name