I am new to SQL and I got stuck at this problem.
There are three separate tables needed for this problem, with relevant information as follows
copies table rentalrates table movies table
movienum rentalcode rentalcode rate movienum title yearreleased
1000 D D 10 1000 Matrix 2001
... D WN 12 ... ... ...
... WN WL 15 ... ... ...
So I am required to display the output of "the title and year released of the movie that has the lowest rental rate" using sub queries, and "order by" is not allowed here.
final output like
title yearreleased rate
matrix 2001 10
My trouble is I don't really know hot to compare the rate and select those movies of the lowest rates.
Any help or hint is extremely appreciated :)
thanks a lot!
This query:
select min(rate) from rentalrates
will yield the minimum rental rate. To go one step further, this query:
select m.title as title,
m.yearreleased as yearreleased,
r.rate as rate
from copies as c,
rentalrates as r,
movies as m
where c.movienum = m.movienum
and r.rentalcode = c.rentalcode
and r.rate = select min(rate) from rentalrates;
will display any movies (title, year, rate) where the rate is the lowest rate in the database.
Related
I want to use a simple private cashflow database. Nothing special.
Therefor I use a table "finance_flow", where I can put all my in- and outcomes.
Income -> amount > 0
outcome -> amount < 0
Table structure
table "finance_flow" with example-data
id
category_id
amount
date
note
int
int
float
timestamp
varchar
1
1
+60,00
5.2.23
use for xy
2
2
-10,00
8.2.23
to Tom for school
3
3
-8,96
8.2.23
milk, bread, cheese
table "category"
id
name
1
tips
2
kids
3
shop
Of course there is a correct foreign-key-constraint.
What I want:
I want some statistical data, for example:
-current status of my money
-total outcomes for each category
-procentual values of those would be nice
I know how to get the total current state:
SELECT sum(amount) as total FROM finance_flow
I know how to get the total per category
SELECT abs(sum(amount)) as total_per_cat, category.name
FROM finance_flow
LEFT JOIN category ON financeflow.cat_id = category.id
GROUP BY category_id [WHERE date = 'february']
(Here I use the function abs(x), because I am not interessted in the sign.
The where-clause is optional, I want this, if the basics are correct, for monthly reports.
How to get the procentual values?
Can I get all this stuff with one query? :)
Expected result:
procentual_per_cat = total_per_cut / total_income(february) * 100
where
total_per_cut = abs(sum(amount)) for category x
total_income(february) = 60
resulting table:
name
total_per_cat
procentual_per_cat
kids
10
16.67 %
shop
8.96
14.93 %
Calculating the percentage is the same a dividing by the total amount:
SELECT
abs(sum(amount)) as total_per_cat,
abs(sum(amount))/(select sum(amount) from finance_flow where amount>0) *100 as percentage,
category.name
FROM finance_flow
LEFT JOIN category ON finance_flow.cat_id = category.id
WHERE amount<0
GROUP BY category.name
see: DBFIDDLE
I have a table of movies and a table of reviews
In my app, I want to show top 10 movies of any genre.
I clearly cannot sort movies just by rating since there are movies with only 1 5 star review, thus only irrelevant movies will be recommended to users.
Currently I receive from DB top 100 movies in this genre sorted by reviews, sort this list by rating on server and only then display top 10.
That kinda works but this solution is impractical in case of e.g. review bombing and moreover, the purpose of top 10 list is to recommend the most relevant movies.
My idea was to add relevance column into the movies table but I've got no clue how to count it:
(amount of 5 star reviews * 5 ) + (amount of 4 star reviews * 4 ) and so on - no
(amount of 5 star reviews * 1 ) + (amount of 4 star reviews * 0.8) + ... + (amount of 0 star reviews * 0.1) - no
total amount of reviews / avgrating - no
((amount of 5 star reviews * 5 ) + (amount of 4 star reviews * 4 ) and so on) / amount of reviews total - mb, I'm not sure what about 0
Moreover, the rating in ratings is not a real number. User can give only 5, 4.5, 4 etc. score review. But what about the situation where users can rate movies like 5, 4.9, 4.8 ... 0.1?
So, how to perform this operation in better way?
[Upd] I think instead of division of smth. we should multiply averagerating and reviews from movies in order to count the relevance (averagerating and reviews are alredy automatically updated on each insert/delete/update). Also we should try to normalize the product.
In this situation movies with 100 reviews of 5 and averagerating of 5 won't beat up movies with averagerating 3.8 but with 57k reviews and also the problem of review bombing will be solved.
Can anyone prove my guess?
I agree with #NickW that this is more of a statistics question than a programming question, but I'll try to answer it, anyway.
If you want to account for both average rating and number of ratings, a straightforward method is to multiply the two. This gives you the sum of all ratings, but, as #qwezxc789 notes, this does not account for the number of zero ratings. Another strategy could be a linear combination of avgrating and reviews. Collinearity shouldn't be an issue because neither variable depends on the other. You could even play around with the linear coefficients to change the relative contribution of each variable. This solution easily generalizes to n independent variables.
Let wi be the weight of predictor i, 1 ≤ i ≤ n, w1 + ... + wn = 1 (or any other constant, but why not use 1?).
You can add this value as a new relevance column in the movies table using the following SQL. I use two equally weighted predictors: ratings and reviews.
ALTER TABLE movies ADD [relevance] AS
(SELECT 0.5 * avgrating + 0.5 * reviews
FROM movies)
I have two tables Medication and Inventory. I'm trying to SELECT all the below details from both tables but there are multiple listings of medication ids with different BRANCH_NO also in the INVENTORY table (the primary key in INVENTORY is actually BRANCH_NO, MEDICATION_ID composite key)
I need to total up the various medication_IDs and also join the tables in one SELECT command and display all the infomation for each med (there are 5) with a total sum of each med at the end of each row. But im getting all muddled trying Group by and Sum and at one point partition. Help please I'm new to this.
Below is the latest non working version - but it doesn't display
Medication Name
Medication Desc
Manufacturer
Pack Size
like i chanced it might.
SELECT I.MEDICATION_ID,
SUM(I.STOCK_LEVEL)
FROM INVENTORY I
INNER JOIN (SELECT MEDICATION_NAME, SUBSTR(MEDICATION_DESC,1,20) "Medication Description",
MANUFACTURER, PACK_SIZE FROM MEDICATION) M ON MEDICATION_ID=I.MEDICATION_ID
GROUP BY I.MEDICATION_ID;
For the data imagine I want this sort of output:
MEDICATION_ID MEDICATION_NAME STOCK_LEVEL OtherColumns.....
1 Alpha 10
2 Bravo 20
3 Charlie 20
1 Alpha 30
4 Delta 10
5 Echo 20
5 Echo 40
2 Bravo 10
grouping and totalling into this:
MEDICATION_ID MEDICATION_NAME STOCK_LEVEL OtherColumns.....
1 Alpha 40
2 Bravo 30
3 Charlie 20
4 Delta 10
5 Echo 60
I can get this when its just one table but when Im trying to join tables and also SELECT things its just not working.
Thanks in advance guys. I appreciate it may be a simple solution, but it will be a big help.
You need to write explicitly all non-aggregated columns into both SELECT and GROUP BY lists ( Btw, no need to use a nested query, and if it's the case MEDICATION_ID column is missing in it ) :
SELECT I.MEDICATION_ID, M.MEDICATION_NAME, SUM(I.STOCK_LEVEL) AS STOCK_LEVEL,
SUBSTR(M.MEDICATION_DESC,1,20) "Medication Description", M.MANUFACTURER, M.PACK_SIZE
FROM INVENTORY I
JOIN MEDICATION M ON M.MEDICATION_ID = I.MEDICATION_ID
GROUP BY I.MEDICATION_ID, M.MEDICATION_NAME, SUBSTR(M.MEDICATION_DESC,1,20),
M.MANUFACTURER, M.PACK_SIZE;
This way, you'll be able to return all the listed columns.
I'm creating a database for Formula 1 drivers/teams. The idea is to display the cost comparisons of team budgets vs team points and driver salaries, to see the effective cost per point for the top 10 teams.
E.g from 2015 info
Team Mercedes
Income received = euro 467.4m (sponsors 122m, partners 212.40m, tv 133m).
Points Scored = 703 (total from both drivers: Hamilton 381, Rosberg 322).
Effective Cost Per Point = 2,506,417.11
I have 3 datatables: One each for the team, the drivers, and a table to join tables 1&2 together, to then create the correct SELECT queries:
Table 'team'
teamid
teamname
sponsors
partners
tv
total
Table 'driver'
driverid
drivername
salary
points
Table 'driverteam'
teamid
driverid
totalbudget
totalpoints
I first need to get the sum of the sponsors,partners and tv so I have created the following SELECT statement:
$sql = "SELECT teamname, sum(sponsors+partners+tv) as total FROM team ORDER BY total DESC LIMIT 10";
I know how to get the salary and points from a driver:
$sql = "SELECT drivername, salary FROM driver ORDER BY salary DESC LIMIT 10";
$sql = "SELECT drivername, points FROM driver ORDER BY points DESC LIMIT 10";
Seems ok, but now comes my problem, how to get the SUM from table 1 and divide it by the points that the drivers have got in table 2.
My limited brain says I need a INNER JOIN using table 3 to get table 1 & 2 together, before performing the necessary divisions etc.
As there are 2 drivers per team, I need to divide the team total budget by each drivers' points, as well as the team total by both drivers points.
What SELECT queries do I need to achieve this?
i m trying to get this:
"Create a view that lists ALL foods with a total consumption for one week. This view is used to help order the food for the zoo animals to eat. Show the food id and name, along with the weekly consumption, the number of animals being fed with each food and the average consumption (weekly consumption divided by number of animals that eat that food) of the food by each animal."
below is my sql query:
SELECT a.foodID
,NAME
,b.qtyperday * 7 AS "weekly consumption"
,COUNT(animalID)
,AVG(( b.qtyperday * 7) / COUNT(animalID))
AS "average consumption"
FROM food a, feed b
WHERE a.foodID = b.foodID
GROUP BY foodID
i can't seem to be able to generate any data for the average consumption which is the final condition
, any solutions??
I believe you need to get the number of distinct animals for each food, e.g.:
SELECT a.foodID
,NAME
,b.qtyperday * 7 AS "weekly consumption"
,COUNT(DISTINCT animalID)
AS "animals eating this food"
,AVG(( b.qtyperday * 7) / COUNT(DISTINCT animalID))
AS "average consumption"
FROM food a, feed b
WHERE a.foodID = b.foodID
GROUP BY foodID
But for further help I think you need to post some sample data and some expected outputs.